I recently came across a problem with floating point numbers. I know there are some inherent inaccuracies, but I was surprised to find a problem with a relatively simple number.

Floats are numbers stored as two parts: a whole number and an exponent. Generally you're dealing with numbers on similar scales, i.e. millimetres or kilometres, so this makes sense.

The term "float" refers to the fact that the decimal point 'floats'. For instance the following are all different exponents with the same whole number:

  • 1.1 is 11 x 10-1
  • 0.15 is 15 x 10-2
  • 1.5 is 15 x 10-1
  • 15000.0 is 15 x 103

Simple enough, but I had a bug with 1.1 - I was getting 1.0999999999989! Odd issue until you figure in that computers think in binary. I didn't expect this to be a problem because both the value and the exponent are whole numbers. What I'd failed to realise is that the floating point was also base-2, not base-10. So the floats above are actually:

  • 1.1 is 154811237190861 x 2-47
  • 0.15 is 168884986026394 x 2-50
  • 1.5 is 3 x 2-1
  • 15000.0 is 1875 x 23

Those horrible big numbers for 0.15 and 1.1 are too big for floats to handle. The issue wasn't really the inaccuracy - I expected the float to only be able to deal with a few significant figures. What was a surprise (and shouldn't have been) was that the numbers it has problems with are not the ones I expect it to. To floats 1.1 is an irrational number.

This normally isn't a problem, for most of the sort of calculations where floating point numbers are used a this inaccuracy is worth the fact that the calculation is quicker.

0

Add a comment

  1. And I'll tell you why...

    The allegory constantly used by governments and the media is on of a household, and the recession is like the breadwinners losing their jobs. Obviously anyone sensible would cut back, yeah?

    But, countries are nothing like households, and that allegory just doesn't work.

    I'm not arguing that they shouldn't cut back at all, but I think a healthy government should be running some degree of deficit during a recession.

    Here are my assumptions:

    1. There will ALWAYS be boom and bust

    We can't stop the cycle of boom and bust, it's been going for hundreds of years and will continue for hundreds more. Maybe one day, but no financial theory to date has come close to a way around them.

    With that assumption we should plan for them: busts will happen. Booms will follow the busts, for a while, until it all starts again.

    During a recession governments should know that, inevitably, a boom will come again. During a boom governments should know that, inevitably, the bust is coming.

    2. Governments benefit from long term stability

    Boom and bust is a vicious cycle and an unstable one: governments have to plan for how much money they have to spend, so instability always messes them up. They have to make guesses as to how much to spend on defence, the police, public health, welfare and so on.

    All but the most extreme libertarians and neo-cons admit on the need for at least some government spending on things like fire services (you might not want to insure your neighbour's house, but if it's on fire you want it put out regardless).

    A governments plans on spending are always guesses - estimates of how much taxpayers will earn and hence how much tax they will pay. A simple fact is that they'll never be 100% accurate, but you want them to be as close as possible. Another simple fact is that boom and bust make those predictions less accurate.

    This means that either a deficit or a surplus is inevitable, we should expect and account for one or the the other.

    3.Tax & spend are inextricably linked to government revenue

    There are lots of theories as to how (and which model is best) but whether you're left or right, and whether you follow Keynes or Hayek, how much is taxed and how much is spent by governments has an effect on how much money people have and how much tax renvue the government takes.

    A government cutting taxes obviously has less revenue, but what does that do to relative wealth? A government cutting spending? They have more money, but public sector employees have less money and government contractors lose business. Less tax is collected - left vs right can argue about whether that is more or less than the amount saved by the cuts, but my point is that it's unpredictable.

    Nobody (including all the best economists) can actually accurately predict the relationship. However it the effect is not one that damps the boom and bust cycle - government behaviour exaggerates the booms and the busts like a binge dieter.

    4. Governments should not have a large surplus

    I think most people expect to be paying a fair amount of tax, and that means the government not having loads of cash left over from the tax they've collected.

    Economic right wingers tend to cut taxes when there is a surplus, governments on the left tend to spend more.

    Something they never seem to do is to try and save that money, partially because elections are coming up and voters want to see something short term, but also because there isn't really anywhere more secure to keep it. You can't really save money in a bank that you underwrite, and if you don't underwrite it you're relying on whoever does.

    For instance in the UK many local councils did have a surplus before the current crisis, which they invested with Icelandic banks. When those banks crashed that British taxpayer money was lost, and (unsurprisingly) Icelandic voters decided not to pay additional taxes to repay most of it.

    Another reason that governments shouldn't save is that they can't get great rates of interest - that comes from taking high risks and someone looking after tax payers' money just can't do that. They have to go for low risk, low payout investments, like gilt bonds.

    5. Governments can borrow more easily than anyone else

    Note that I'm not saying that it's always simple - governments can fail to the point where they can't borrow any more, but that's rare compared to that happening to people or companies.

    Maybe not if it has come from Greece, but as a general rule government debt is still one of the safest investments. Much as the news goes on about governments going bust, most of countries can borrow money for a lot lest interest than most people pay on their mortgages.

    Right now the UK government can borrow (i.e. issue bonds) at 0.5% that will be paid back in 10-15 years, well into the next boom. What's the best mortgage or loan you can get?

    Putting it all together

    For governments to benefit from long term stability they need a plan that always works. They shouldn't be savagely cutting back or raising taxes in the recession and obnoxiously binging or reducing taxes in the boom. If tax and spend is linked to GDP (as assumed above) then alternating cutting and binging could make it all worse.

    You want a tax and spend strategy that uses the boom times constructively and weathers the bust times as well as it can. If that's the case then the tax paid and amount spent should stay fairly constant. If you're left wing then that's high tax and high spend all the time, if you're right then that's low tax and low spend all the time. Either way, it should be fairly constant.

    If the tax and spend system is constant then there will be either a boom surplus or a recession deficit. You either have to plan for surplus during the boom, or plan for deficit during the bust.

    I don't believe that governments can help themselves during a boom. They will always blow that surplus on something stupid, like Millennium Domes, or weapons programs, or wars, or massive tax cuts, or something even dumber. They have an election to win every 4 years and the financial cycle is 10-15.

    Even if they save the cash, there's not really anywhere safe to put it.

    So it is my conclusion that they should break even during the boom and pay off the debts that they built up during the bust. During a recession they shouldn't panic and change all the plans, instead they should run into debt while the economy recovers and pay it off when the boom comes.

    0

    Add a comment

  2. The UK will vote on May 5th on whether to switch to the Alternative Vote system (AV) rather than the current First Past The Post (FPTP). I'm a supporter of AV, but FPTP has huge support from both the major parties and from Rupert Murdoch, which means that it both doesn't have a chance and must be the right way on principal.

    Fact is anything legal that Murdoch's against I'm for on principal.

    There has been a lot of misinformation about this: lots of bad examples in every media outlet trying to make AV seem much more complicated than it is, and no clear explanation as to why anyone would want the switch in the first place.

    So here's my go: imagine a typical UK voting scenario at the next election. There are 6 candidates:

    • Conservative - centre right, currently in power, conflicted on EU.
    • Labour - slightly less right than the Conservatives but more authoritarian
    • Liberal Democrat - centre left, but lie a lot.
    • Green Party - left wing and pro environment, but tiny.
    • UKIP - right wing and isolationist.
    • BNP - left wing and openly racist.

    FPTP

    Under the current FPTP system you cast your vote for one of the above, but you have a problem if you don't support either of the top two.

    For instance I'm left wing, but I don't think much of the Labour party. The Green Party is closest to my political views. However, a vote for the Greens is a wasted one - only Conservative and Labour have any real chance of winning. I end up voting Labour, as despite the fact that they're my third choice I would still rather see them win than the Conservatives.

    This tactical voting isn't only a problem for me - suppose that someone is right wing economically but prefers UKIP's stance on the EU to the Conservative's? They'd have to vote Conservative tactically too.

    In both cases the relevant mainstream party claims the voter's support - there's no visibility that they were nobody's first choice.

    Despite all that tactical voting most voters will have gone for someone other than the candidate that wins - with 6 candidates that could be less than 20% of the votes!

    AV

    So under AV that changes - instead of one X in a box we put all 6 candidates in order. I put my first choice down as the Green Party, then Lib Dem, then Labour. My right wing counterpart chooses UKIP, then Conservative.

    1. Greens have the fewest votes - my vote falls back to Lib Dems, my second choice.
    2. BNP have the next fewest.
    3. UKIP are next - my counterpart's vote falls back to Conservative.
    4. Lib Dems are next, so my vote falls back again, this time to Labour

    So after all that we still have either Labour or Conservative, but with two very important differences:

    • The winner has 50% of all the votes cast.
    • Everyone gets access to the voting stats, so everyone knows how much support each party actually has.

    That second point is important for all the smaller parties - for instance the BNP would see that they have a very small number of first choices and that everyone else lists them last (incidentally the BNP are dead against AV, despite what the anti-AV lobbyists say). Lots of small single issue parties would be able to show that there is support for their issue, even if not enough to elect them on that alone. Lots of alternate parties like the Greens and UKIP could accurately gauge their support. Lots of independent candidates could stand despite not having national backing.

    Most seats in the UK don't have that much choice - my local MP at the last election was a choice of Lib Dem, Labour or Conservative, and the Conservative's took it by a very slim margin. Arguable the left-wing vote was split across two parties while the right-wing voter only had one choice. Likewise there were plenty of seats with a choice of Labour, Conservative or UKIP where Labour got in, this time because the right-wing vote was split.

    In fact in the last election there were several marginal seats where smaller parties didn't even field a candidate for fear of splitting the left or right voting blocks.

    More fine grain choice of political parties shouldn't reduce your chances of success!

    So why are the big parties so against this? Well, long term it breaks down their monopoly - it will be easier to gain support for smaller parties. It will make election outcomes considerably more unpredictable - MPs will have to work harder for your vote because it will mean more. Surely MPs having to work harder can only be a good thing?

    0

    Add a comment

  3. There is a problem in UK banking that's stalling our recovery and it goes something like this:

    • Banks have two main components: high street lending & saving, and investment banking.
    • The investment banking side took far too many risks in dodgy sub prime investments and lost all the money.
    • However if the high street lending & saving side of a big bank fails it does huge damage to the economy, so the government steps in to fill the gap.
    • Now the banks are required to shore up their investment banking risks with actual capital so that they don't need bailing out again.
    • They don't have this capital, so while they slowly build it the high street lending & saving side doesn't do any lending - getting a mortgage in the UK at the moment involves having a massive deposit, ridiculous booking fees and unfair rates.

    So how to fix this and get them lending again? The UK ConDem coalition is talking about breaking up the banks - splitting the risky investment lot (increasingly referred to as 'casino banking') from the 'too big to fail' component.

    The banks hate that idea of course, threatening that the banking business will leave the UK (oh no! You might leave with your middle man industry that processes huge amounts of money but doesn't actually make anything or pay much tax? How will we cope? ;-)

    Unfortunately you don't get into politics without paying for marketing and that money comes from rich folks who are tied up in the banks, so while telling the banks to 'do one' appeals to all of us voters it doesn't appeal to the politicians' paymasters.

    I don't think they need the conflict though - there is another way. The 'too big to fail' component, the actual high street lending & saving part of the banks, doesn't need to underwrite massive risks. That's the component that the government actually needs to underwrite, so why not give banks the option:

    • If a bank has a casino investment arm then it has to underwrite all of its actives with its own capital.
    • If a bank doesn't have a high risk component then the government underwrites it and they only need a fraction of the capital.

    This would give banks the choice: they split themselves up and they can start lending again right now (and making lots of money on the interest), or they keep their high risk/high reward component and risk their own money.

    0

    Add a comment

  4. British Airways have the best paid flight staff in the world. Their pay is sky high (sorry) – cabin crew can earn up to £56k a year! To put it in context that's more than junior and mid-level doctors – I really don’t see how any cabin crew job can be worth more than even the most junior doctor's role.

    British Airways plane

    BA also run one of the biggest teams per flight – they have 14 on each long-haul plane.

    The problem is that flights on BA are expensive. You would only ever fly them short-haul if you didn’t care about the price – that means business users and the rich. Everyone's tightening their belts at moment, and fewer people are choosing the (admittedly high quality) expensive BA.

    So BA needs to cut costs – they're losing money (£401 million last year and £292 million in this year so far) and they need to do something about it. They have the highest running costs of any airline. They also have a huge pension deficit, but that’s for anther post. Their plan is to reduce the number of cabin crew on each flight.

    They're not asking their overpaid-against-the-market employees to take a pay cut, they're not making redundancies. Yet the unions have kicked off and over Christmas BA faces a 12 day strike.

    This strike will really hurt BA – a company that's already bleeding. Just the news of this strike is driving away their business. For a company that relies on a high quality, high cost strategy this loss of faith in them could go on hurting them for a while.

    I really believe in the values that unions represent – there should be a way of ensuring that all staff are fairly paid. I bet that BA has all the inequalities big companies often do: whatever cabin crew are paid it must still be galling to be told that "times are tight" and so on from a director who's earning ¾ of a million pounds, regardless of how fair that is as a director's salary.

    However in this case I suspect that the 12 day strike too far, and I think part of the problem is the whole concept of a generalised union. The fact is that the employees are actually stakeholders in the business – if BA fails they could all lose their jobs. However the union itself is not a stakeholder, despite being driven by employee voting. The relationship between employers and unions is often portrayed as adversarial, but it shouldn't be. It should be in the union's interest for the company to make more money, and it's then their job to fight for a bigger share of that money for the employees. When the union action causes the company that's already losing money to lose yet more money then surely that starts to put jobs at serious risk?

    My personal opinion is that employee ownership is by far the best way to go – especially for bigger companies. However I accept that's not going to become the norm any time soon, so how can we ensure that unions act in the interest of the employees and the company?

    There should be one union per large company. They would be a fully fledged and separate organisation and run the way most unions are. One major caveat though: that union is tied to the company – if the company goes bust then the union ceases to exist. The union could still fight for employees' interests, but would also need to be mindful of keeping the company competitive.

  5. Recently at TechEd Berlin I attended an optimising Javascript presentation that I described as having "lost focus".

    I think this one (from Google) is far more the sort of level and detail that I expected:

    This presentation is excellent - in fact I think every developer who ever does any Javascript should view it.

    0

    Add a comment

  6. I think the current situation with bankers' bonuses shows a complete failure to understand risk and how markets actually work.

    There's a TV show in the UK called Property Ladder. Every week through the property boom it followed someone buying and renovating a house with a view to selling it for profit. They found some proper idiots on that show. The resident expert would explain that putting a toilet off the kitchen was a bad idea and why waste £20k on a strange round window when it won’t add to the sale price. Every week the amateur developer would ignore them and do whatever stupid thing it was anyway.

    However, as it was a massive boom market, every week they made loads of money.

    In short, in a boom market any idiot can make money.

    They’ve now renamed the show to Property Snakes & Ladders – the people on the show now listen to the excellent advice and really struggle to make a profit.

    For 10 years we've been rewarding high risk behaviour in a boom market and calling it talent, or skill, when it really wasn't. The way that reward is structured is based on some really dumb assumptions.

    What do I mean by dumb assumptions? Let's look at an example:

    • Suppose an investment banker is dealing with £1,000,000,000
    • They manage to make 5% on a transaction
    • That's £50,000,000 profit!
    • Their cut would be 20% of that, or ten million pounds!

    That all looks reasonable, right? I mean, if they hadn't done their thing you wouldn't have made anything. Maybe you would take off the interest you could have made anyway in gilt bonds or something low risk, they'd still be making you tens of millions so their cut is fair.

    Except this misses something fundamental – something missed by every Nobel Prize winning Economist for the last 20 years (which is incidentally why the Nobel Prize is a joke).

    What was missed? Well, the whole of the £1,000,000,000 was at risk – all of it could have been lost in the deal. Not just 5% or so, not even half, all of that money could have been lost.

    What's happened in our banking crisis is basically that – deals that used to make 5% in a boom market suddenly lost 90% instead, and everyone in banking was surprised because they thought the sun would never stop shining.

    In the various bailouts by various governments have basically underwritten this risk – I'm not sure that they had a choice as the banks really are "too big to fail". However as the government is essentially underwriting the risk where is their cut?

    I have a simple solution to this - in future any transaction that is too big to fail – i.e. where the government and tax-payers are implicitly underwriting the risk the banks should be levied with:

    • A 10% tax on profit that goes to paying off the government's debt on the bailouts.
    • A maximum 0.5% cap on any bonus paid (note that in my example above that would still be £250,000)

    If the bankers' don't like this they can take their 'skills' elsewhere - this is the cost of us underwriting their risk.

    0

    Add a comment

  7. RBS logo

    There's a great deal of fuss at the moment about RBS's investment division's planned bonuses. They've made some money (great!) but want to pay over a billion in bonuses, which is over a quarter of the profit.

    As the UK tax-payer owns 84% of RBS there is quite rightly uproar about this – why are we paying the wealthy fat-cats that we just had to bail out? However the RBS executive team are going on about how they need to pay these bonuses to keep the best staff, and that they’ll lose all the talented bankers to competitors. They argue that any control of bankers' bonuses should be across all banks, because otherwise they'll lose any edge. They're threatening to resign over this - they won't of course, but it gets them in the papers.

    Both sides seem to have compelling arguments, leaving our government with a stark choice:

    • Block the bankers' bonuses, which might win votes (or at least not lose them) but will result in all the best bankers leaving, and hence RBS will make less money.
    • Pay the bankers' bonuses, which will definitely lose them even more votes but will keep the best employees and in the long term RBS pays the tax-payer back sooner.

    The problem is that the fundamental assumptions here are just plain wrong for two reasons:

    • 25% of all the profit is an insane amount to pay as any sort of bonus. What – I risk my entire capital (not just some of it - I risk every single penny) on your investment nouse and you take ¼ of my profit? I'm sure you know where you can stick that deal.
    • The assumption that the 'good' bankers will leave if not paid the bonus is wrong. These are highly paid people already, so the ones that leave will be those whose priorities are skewed to the big risks for big rewards.

    I've argued this second point before – would you leave a good, very high paying job, for another that might not be so good (or might go very wrong) but the pay was silly money? I'm sure a million pound job looks pretty appealing, but if you're already earning hundreds of thousands do you really want to take the risk of the new job?

    The sort of person who takes a big risk for this kind of reward is specifically the sort of person that I don’t want looking after my money! It’s exactly that kind of high stakes gambling that got us here in the first place – why would we want to reward that?

    It's just not good business practice to pay inflated amounts for things that don't really do you any good.

    Cancel the bonuses (or knock them down to something that makes sense, like 1% of profit), wave goodbye to the risk taking bankers that leave and take all that profit to start paying back the tax-payer.

    0

    Add a comment

  8. When .Net originally launched it came with first rate support for Simple Object Access Protocol (SOAP) and at the time I was seriously impressed. Creating a SOAP client-server connection was amazingly easy - little more than adding a .asmx file and decorating your methods with the [WebMethod] attribute, and then point your client project at it and Visual Studio does the rest.

    What Visual Studio actually does in this case is create a large auto-generated code file from the WSDL. The WSDL is also auto-generated for you and is a detailed description of your service.

    All great, except that it leaves you writing a complex API as part of your web project and requiring an awful lot of auto-generated code to consume it.

    Enter Windows Communication Foundation (WCF). With WCF it became possible to specify a service contract – an interface that both the client and server could have that described the API. WCF also moved all description of the actual transport into configuration files – technically it became possible to write one set of code for your client and server, and then decide at run time whether to use HTTP, secure sockets, named pipes or whatever to connect.

    The problem is that when I say technically I mean really, really technically: even an expert WCF programmer could end up struggling for hours to get both the server and client config to match. In addition there were only ever a few of the amazing array of options ever used: HTTP or HTTPS? GZIP compressed or not? Get any even slightly wrong would result in hard to investigate errors.

    Our client software was intended to be installed and set up by users that weren’t WCF gurus. With a little help from stackoverflow.com I got an auto-config script that worked, but it was still far too much of a coding mess.

    However that isn’t the biggest problem with WCF and SOAP – the whole point of SOAP is that it’s universal, an open standard based on XML that anyone can support, right?

    Well, no. SOAP is vastly over complicated and the only provider with even remotely complete support for it is Microsoft. Try consuming a complex WCF (or even worse a high-security) service across SOAP from a Java client and your problems are likely to be myriad and involve many dirty workaround hacks. We had Flash components built in Flex and ActionScript that consumed WCF SOAP and found ActionScript’s support to be weak at best. Forget about anything with Javascript.

    Basically, SOAP might be this powerful open standard with built in API auto-discovery, but no-one really supports it except Microsoft.

    Why?

    Well, it turns out that while Microsoft was getting behind SOAP everyone else was getting into Representational State Transfer (REST). The REST model is far simpler: use what HTTP already does. The HTTP protocol already has functionality to get content, upload content and make changes to it; it already includes security (in SSL) and compression (in GZIP). Why re-invent the wheel?

    The downside of REST? We lose the WSDL descriptions, so no more auto-discovery and relying on Visual Studio to create everything for you. However all REST APIs are structured in the same way, so it’s usually easy to figure out how everything works.

    The great thing about REST? My service can be reached by .Net, Java, Javascript, ActionScript and even spoofed with browser tools like FireBug and Fiddler.

    So Microsoft backed the wrong horse. However they’ve realised this (they normally do, eventually) and have started to add first rate support for REST into both ASP.Net MVC and WCF. I'm going to investigate these new approaches, but either way I think it's time to give up on SOAP.

    0

    Add a comment

  9. Sightseeing

    By this point we were starting to feel the tech-fatigue. We took the opportunity to see a little of Berlin, before heading back to hit the labs and the convention stalls

    DEV301r Microsoft Visual Studio Tips and Tricks

    Scott Cate

    Nice session to finish on - most of these I knew already but a couple were new. They're all on Scott's blog.


    Finally all the stands that had prize draws held their raffles. Oddly the winners on every single stand were right at the front of the fairly large queue. I suspect that most were very poorly run and some developers wasted their conference entering the same contests over and over again. Apparently one guy won 4 laptops!

    Overall

    I feel that Tech Ed was productive - I've learnt a couple of new things and it's got me excited about VS2010. However I think that they've swung it a little too far to the IT professionals. There needed to be many more serious technical sessions - I only saw one session on C#4, two on ASP.Net 4 and one on MVC 2. I think the only new technology I was happy with the coverage of was Silverlight 3.

    The food, facilities and general organisation were all excellent, but the labs were a let down: annoying US keyboards and very prone to crashing (even for virtualised beta software).

    Finally finishing on Friday 13th was a good idea - my flight home was very cheap ;-D

    0

    Add a comment

Label Cloud
Blog Archive
About Me
About Me
Blogroll
Blogroll
Loading