Hacker News new | ask | show | jobs
by tzs 5107 days ago
> Let's pretend he said integer since floats for money is outright broken.

This reminds me of a story I read on Reddit that someone told about his dog. The first time his dog saw a horse, the dog was excited, and ran up to sniff the horse through the fence.

It was an electric fence, and the dog touched it with his nose. The dog found this extremely unpleasant.

Now the dog is deathly afraid of horses, and runs and hides whenever he sees a horse.

1 comments

You're being obtuse. What's your use case for money as floats?
On some 32-bit machines, a double precision float often exactly represent a larger range of integers than the integer types can, which makes it easier to avoid overflow problems you can get if you work in integers.

Of course, one might argue that the programmer using integers should be aware of this, and code accordingly, or else he shouldn't be writing code dealing with money (or any other thing were failure can have serious consequences).

However, the same applies to floating point. Floating point is not magic. A programmer who understands it can safely use it.

Many programmers seem to get burned early in their careers by using floating point without understanding how it differs from real numbers. Then, like the dog concluding that the horse, rather than the fence, was the problem, these programmers conclude that it is not safe to use floating point instead of properly concluding that they should not use tools they don't understand.

I think his point is that the OP got burned using floats for money. He thought the lesson was to use a custom class for money every time, but the actual lesson could have just been to use integers instead.
Actually, the point was don't blame your tools.

If you understand how floating point works, you can deal with the rounding and truncation errors, and get accurate results for monetary calculations.

Ah right, that makes sense.
Realtime trading systems.

If your system is slow, you lose money. If your trading system says you earned $1,523,374.54, but your accounting system says you only earned $1,523,374.26, you don't care much.

I'm genuinely curious here: why would using integers be slower than using floats? I thought floating point operations were always more expensive than handling ints.
For simple accounting, it wouldn't be slower. The issue is analytical code, e.g.:

    int price = getPrice(symbol);
    double signal = exp(...) * ((double)price);
    if (signal > threshold) {
        buy(symbol);
    }
The point is to avoid converting from int to double every single time you need to do a calculation.