87 points · by cpeterso · 4y ago · 108 comments
Real world practicalities limit the the need for extended precision in a lot of (if not most) cases.
For example, most monetary transactions are settled to the nearest penny. Most time clocks are only accurate to the nearest second. Most milling machines are only accurate to a single digit fraction of a millimeter.
Applying extended decimals to these may work --- but in engineering terms, this is really "false accuracy" that is unnecessary and can be counter productive.
It's much nicer during mixing, editing and other production steps to work with floats and so essentially all modern software does that, even though the A2D conversion is integer and the end results will be integer data (e.g. CD audio is Linear PCM 16-bits at 44.1kHz)
That means you can raise and lower the volume on signals over and over without significant precision loss.
Said every developer who has ever applied floats where scaled integers would be just as effective.
I attribute this to pocket calculators which have shaped most people's thinking.
I've even had developers try to tell me it can't be done any other way --- until I show them.
All that said, if floats are needed to interface with other software, you may not have much choice in the matter.
With a conventional analogue recording medium, the medium has physical properties which impact the precision with which it can record audio. For example maybe the reel-to-reel tape recorders in a studio can do about 12-bit precision. At the bottom, the precision is cut off by noise, mechanical noise in the equipment and eventually even quantum mechanical noise in our universe which is unavoidable. At the top it's cut off by practical engineering limits - the magnetic field strengths are limited. A good analogue engineer ensures that there's "headroom" where if the recording is a little louder than expected it doesn't bump into that upper limit, when Aretha hits that note 6dB louder than anticipated, you had 10dB of headroom so it's captured OK. But to do this you're sacrificing that precision at the other end of the scale, listeners can't hear her turning the lyrics sheet in the background of the song even though you'd have heard that if you were in the room.
In digital integer space, we can have lots of precision, 14-bit happened early, 16-bit was soon common place, and today 24-bit is widely available (although you need to squint to see 24 actual bits, don't think about it too hard). But, the integers are brick walls at the edges of that range. If you set things up to use all your (say) 16-bits and it comes out hotter than expected, your data is trashed because it saturates † producing a harsh clipping. So you need to carefully set the headroom to give you as much space at the top as you need, but without wasting too much. Stressful.
With floats you get infinite headroom. Conventionally PCM audio is represented as -1.0 to 1.0, but in float space if you're "too hot" by a factor of literally 1000, it's no problem at all, floating point numbers can go from -1000.0 to 1000.0 just fine, and when you're ready to actually listen to it, just multiply them by 0.001 (this is called "gain" in audio).
† Or, if the programmer doesn't understand what they're doing, it wraps and sounds like complete nonsense. This is common on 1980s home computer audio setups.
Said every developer who has ever applied floats where scaled integers would be just as effective.
Floats are great to prototype quickly and get a good result. Once the algorithm is found, you can spend more time fine tuning with improvements such as others kinds of ways to represent fractional numbersYou gave the example of a milling machine, of course in most cases you wouldn't expect it to be accurate to more then a 10th of milliliter. So you could believe that e.g. 100th of a millimeter should be more then enough as your scaled integer (meaning an integer with a value of "100" represents one millimeter). The maximum value of a 32bit integer would represent around 43km. Who would ever want to use more?
But what if now you are trying to calculate the 3D distance between two points which are about a meter (= 1000mm = (int)100000) apart in one direction. To calculate this you need a third power. 100000^3 is pretty large, much larger than a 32 bit int can hold...oops
With scaled integers you have to constantly think about whether each intermediate result is still within your range. It is a terrible, headache inducing format for many applications. The magic of floats is that you do not need to worry about so many things. Yes, they have their pitfalls, but they are used for a very good reason and "you don't need the precision" simply is false in many cases.
Settled, yes, but all kinds of financial operations require higher precision. IME with payment processing the backend calculations and account balances were done to a thousandth of a cent. It was a common point of confusion because when clients were billed for their processing fees they usually ended up with a fraction of a cent balance that couldn’t be billed and stayed on their account. Every couple of months those fractions of a cent would add up to a full cent and their detailed billing breakdown would include a 1 cent charge in the “other” category that would drive them crazy. But of course financial calculations usually don’t use floating point anyway.
Do this continuously and consistently and you can easily avoid the "mystery" penny problem.
I also overstated the customer impact... perhaps 1% of customers would inspect every detail of their statements and they tended to be annoyed by it. The overwhelming majority didn't notice or care.
I spent several years maintaining a C library that handled these for some embedded instrumentation. This included most key mathematical functions as well. Most interesting thing I ever had to look after.
One 3 line function can handle applying an interest rate to monetary amounts held as scaled integers. Instead of taking the time to write this one function, the typical developer will build the entire software around floats which causes endless issues.
Even the most naïve calculation, such as computing total amount paid at 8% compounded monthly over a 30 year mortgage, ends up wrong by over $100,000 compared to the correct answer. This is a pretty common mortgage calculation.
Here's the expression to evaluate: 1000000 * (1 + (8/100)/12) ^ (12*30). Do it, rounding to d digits of accuracy at each basic expression, and here are the errors you get:
2 -> 25 million
3 -> 1.3 million
4 -> $131,170
5 -> $13,040
6 -> $1304
7 -> $130
8 -> $13
9 -> $1.3
10 -> $0.13
11 -> $0.013
....
Thus, using anything less than a double, over large portfolios, is a terrible, terrible idea, even for such a simple calculation.Anything actually useful, such as summing such calculations over some portfolio, or handling sum over variable interest rate calculations, or, well, pretty much anything, completely pukes at 4 decimals.
This is why people that don't develop floating point with a solid understanding of how to compute and check things like condition numbers for calculations should not give advice on how much precision to use for things.
In fact, I'm hard pressed to find any reasonable financial computation that is not crap at 4 decimals.
This is perhaps why your "guess .. that at least half of the cases where floats are applied could be better served using scaled integers" is not a very good guess.
The proper answer is do not pick either unless one really understands the numerics, so if someone chooses "scaled numerics" over floating point because they find floating point complicated, then they are most certainly made an uninformed choice and likely an error.
Choosing floating point calculations over scaled numerics is much less likely to bite someone doing numerical math, since it can scale properly and dynamically to help hide their ignorance of numerical issues.
Most simple accounting applications involving time and money can be better addressed without them.
Go follows the standard. However, this creates an issue [3]. Indeed, NaN can map to an infinite number of values. These values cannot be accessed. +0 and -0 designates a unique key.
JavaScript normalizes -0 to 0, and NaNs are normalized to a canonical NaN. This makes possible to use NaN as a key in a map.
Other implementations could rely on binary comparison.
This is a lot of pain to deal with. It is better to avoid float comparison or to restrict floats in some way.
[2] https://lists.sr.ht/~sircmpwn/public-inbox/%3CCAFFTG-a-Vci%2...
For example, if you go to https://www.h-schmidt.net/FloatConverter/IEEE754.html and enter 1.0. Then use +1 and -1 to go through ULPs.
julia> 1.4 + eps(1.4) === nextfloat(1.4)
true
julia> bitstring(1.4)
"0011111111110110011001100110011001100110011001100110011001100110"
julia> bitstring(nextfloat(1.4))
"0011111111110110011001100110011001100110011001100110011001100111"It's unfortunately very common for people to misguidedly treat it as an absolute error which makes no sense if you pause to think how it's derived and what it really means (the limit of the significand window, aka mantissa, i.e 2^-52 for a double)... that and the fact that if it's a constant it cannot possibly be an absolute error when the exponent is separate from the significand. There are libraries that have implemented conditions with macheps as an absolute, it's on my todo list to try convince the maintainers of such libraries that's it wrong, but it's a tricky subject to explain while also being massively underestimated by most, so I don't relish it - combined with the fact that checking against an arbitrarily very small absolute does happen to fix a lot of comparison errors - just not for the reason they think, and not reliably.
One point which often bites people which isn't highlighted in this article, is that due to having an explicit sign bit 0 and -0 have different encodings, but in most cases you'll want them to compare equal. So just comparing the bits won't do.
IIRC even the .Net CLR had this issue way back in the 1.1 days.
For some problems, it can often make sense to switch to arbitrary precision numbers, at least for some parts of the calculations.
Wait, when did HN become reddit?!
How does JS do it? (0 / -1) === (0 / 1) is true.
const n = 0/-1, p = 0/1;
n === p; // true
1/n === 1/p; // false
1/n === -Infinity; // true
1/p === Infinity; // true
Infinity === -Infinity; // falseNot at all... but I think there are a large number of people who think they can imagine a better format and yet don't fully understand or appreciate much of the design of IEEE754, and they tend to be quite noisy.
I think the lack of appreciation is ironically due to how damn good a format it is. It manages to hide the myriad deficiencies through such a good balance of compromises that it casts this illusion that perfect fp math is possible in a generalisable enough way. So on the occasions it surfaces the true reality, people assume it must be some kind of defect that is easily addressable with a new format; rather than an intentional decision to maximise correctness and utility by carefully choosing where and how to be incorrect. FP math is the most underestimated areas by programmers IMO, it's just taken for granted so much, which is probably a testament to how well IEEE754 works.
Giving people the illusion that they can work with real numbers on a computer by itself is pretty magical. But the fact that 32bits of data are not enough to hold information about all real numbers and that floats aren't actually real numbers should not be surprising. To me it seems most people don't even understand what floating point numbers are, if you know a little bit all the "weird" behavior starts to make sense and you understand why it has to be that way and how much thought and genius has been put into this datatype.
> Tiny discrepancies don't randomly appear during float operations
They don't "randomly" appear, because as you say IEEE 754 is well-defined, but discrepancies _do_ appear, and if you care about the concept of equality, they certainly matter.
Take a trivial example in C:
#include <stdio.h>
int main(void) {
volatile double a, b, c, d, e;
a = 5.0;
b = a/3.0;
c = b/3.0;
d = c/3.0;
e = d*27.0;
if (a==e)
printf("EQUAL\n");
else
printf("NOT EQUAL\n");
return 0;
}
I think everyone would agree that 5 / 3 / 3 / 3 * 27 = 5, or in general that a / 3 / 3 / 3 * 27 = a. But this program, when executed on a system properly implementing IEEE 754, will report that a and e are not equal. Their bits are different.Hence why when you're talking about comparing equality of IEEE 754 values, you can't just do a comparison of the bits in storage.
You're right that all (correctly implemented) systems will accumulate errors in the same way (assuming you've selected the same rounding mode, etc.), but I don't see how that negates the need to handle the fact that the representation in memory of e will not equal a even though they _should_ represent the same value. Given the sequence of operations performed, how much "slop" should you allow when comparing a to e? Certainly more than 0 which a bit-by-bit comparison implies.
That’s not true. One of the features of IEEE floats is the existence of NaNs that aren’t (according to the standard) equal to themselves.
More often than not, the error is relative wrt the greatest magnitudes in the intermediary calculations. In essence, if you subtract two floating point numbers, you’re kinda screwed, because you cannot ever handle with good precision cases like A - B, where A and B are big enough numbers. Not to mention more complicated operations like trig functions.
In my opinion, one should avoid floating point as much as possible. And not only when testing for equality (all comparisons suffer from this).
Or, of course, ignore FPEs and proceed at your own risk.
This is not a problem with floats. This is an
inherent* result of the design constraints. You can not fix it and there are no alternatives without this flaw which offer any of the same benefits as floats.Any operation between two floats is the floating point number which is closest to the result calculated as real numbers, that is the magic of floats.
Floating point numbers are a near magical type, which for many applications are not only a good choice, but the only one which makes any sense. It is near impossible to imagine modern engineering without them.
One good common example is numerical integration. In any sufficient fine grained posteriori simulation, even with modest limits on position - delta velocity can be too small to preserve when adding to position, i.e when delta velocity is more than 2^52 smaller than position. Keeping a separate accumulator is the only way to handle this without arbitrarily increasing precision with software FP.
https://news.ycombinator.com/item?id=33299829
Links to an excruciatingly thorough treatment of the subject by David Goldberg:
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.h...
should have the 2017 tag.
hi Matt :)
To illustrate, here is some gold a friend recently showed to me: `float i = 1.F; while(i <= 10.f) { do_something_important(array[(int)i]); i+= 1.f; }`. We both died a little bit (though maybe only I did, because he sees stuff like that too often).
- The representable values are so dense near zero that there will be less practical difference between strict equality and approximate equality. Strict equality would be theoretically significant if you found it, but not really necessary to check for. You'll see mostly false negatives.
- The representable values are so sparse far away from zero that strict equality isn't really valuable theoretically or practically. You'll see mostly false positives.
So perhaps there is a region (the location and size of it depending on what you're modelling), where strict equality is just likely enough that you need to check for it, AND that the ULP at that point is meaningful for your application. But philosophically, in that situation, are you really comparing them for equality, or does your epsilon just happen to be zero? Would it be better to interpret your question as: are there situations where you want to check for strict equality no matter what either of the values are?
Things which are genuinely representable as a float value testing for equality is very rarely useful.
If you think about it, people use 64 bit doubles for representing latitude and longitude. They don't have a lot of precision. A second of a degree is about 25-30 meters (depending on where you are. that's 1/3600th of a degree. So five decimal points gets you there. With 64 bit numbers, you can probably get to cm/mm level accuracy. Which is plenty considering GPS is not accurate to more than about 5 meter.
And distance algorithms are tricky too; they are not that exact. The earth isn't a perfect sphere.
So, you are dealing with an inexact representation of doubles that weren't very exact to begin with and the algorithms add more errors. The solution is to not compare equality but distance with some margin of error. So, subtract your expected and actual values and assert that their difference should be less than whatever margin of error is acceptable to you.
SELECT foo_id, foo.some_float, SUM(bar.some_thing)
FROM foo JOIN bar USING (foo_id)
GROUP BY foo_id, foo.some_float
I feel kinda dirty whenever I do this.Though, I would guess the optimizer (at least in postgres) is smart enough to ensure no float equality checks actually happen under-the-hood. They could be necessary, if the schema was different than I'm imagining; but maybe in that case, it would almost always be a bad idea.
Though I have seen some people using a double as a primary key (no idea why) and some database engine (internal, not major vendor) failing to do equality comparisons in certain statements, I suspect because they must be switching to "close enough" which is not what you expect when you write col1 = col2.
I've always liked the way MySQL/MariaDB let you omit things from the GROUP BY if they're provably unique in each group (here, if foo_id is a primary key of foo, and you're grouping by it, there can only ever be one foo.some_float for each foo_id).
I suspect in practice this would get rid of approximately all occurrences of group-by-float.
When they are integers. By construction, floats provide exact arithmetic for small ints. It makes sense to compare those for equality.
Also, when defining a ``sign'' function, you may want to treat the equality case separately, to avoid introducing biases when the input data is quantized.
If you do exact comparisons for any non-trivial cases, you'll find different compilers, optimization settings, runtimes, and processors give different results.
It would be a lot slower, too, and wouldn’t work. How do you define “compare the result”? The strings “0.0” and “-0.0” would have to be equal to each other, and the string “NaN” not equal to itself, “1000” larger than “0.999E3”, etc.