6 ms·
Comparing doubles with == ?
by alexfoo 9y ago
Comparing doubles with == ?
- half-kh-hacker 9y agoI'm not versed in C#, what should you use otherwise?
- philh 9y agoIt's not a C# thing, it's a floating-point thing. Two numbers which mathematically "should" be equal, might not be due to rounding errors. (In python, 0.15 + 0.15 != 0.1 + 0.2.) So it's risky to compare them with ==, sometimes you'll get the result you expect (and sometimes you can be confident of that) but sometimes you won't. If you can't be sure, you should compare that they're the same within some threshold, but that has pitfalls as well. (I feel a little silly saying "it's not a language thing" and then "in python", but there may (or may not) be various implementation details which other languages might use to get a different result.)
- smitherfield 9y ago`0.1 + 0.2 != 0.3` is a property of all (base-2) floating-point arithmetic, no matter the precision or programming language.
- estomagordo 9y agoWell yeah, but this was 0.1 + 0.2 != 0.15 + 0.15, and there's no obvious reason why 0.15 + 0.15 = 0.3 imo.
- philh 9y agoI interpreted their comment as "here's an example that will always work", and I appreciated it in that light.
- xioxox 9y agoThat's absolutely fine if they are set with explicit values or were assigned with the same double. The main issues used to be with the old x86 80 bit wide floating point registers which meant you could sometimes find x != x depending on whether the number went to memory and back.
- twic 9y agoThere's also oddity around NaN - if x is NaN, then, on a compliant chip, x != x regardless of whether it's ever visited main memory. If you find some reason to use a NaN inside one of these GeoPoints (at one of the poles, perhaps), and the equality of them depends on the equality of doubles, then you may give your users a bit of a surprise.
- maccard 9y agoNothing wrong with it, if you know what you're doing. [0] and [1] are great articles on the topic [0] https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ https://randomascii.wordpress.com/2012/02/25/comparing-float... [1] https://randomascii.wordpress.com/2017/06/19/sometimes-floating-point-math-is-perfect/ https://randomascii.wordpress.com/2017/06/19/sometimes-float...