4 ms·
No, addition is still commutative (i.e. a + b == b + a) Sadly, it is not associative (i.e. (a+b)+c != a+(b+c)) Imagine a being a large number, and b and c bei
by jabot 9y ago
No, addition is still commutative (i.e. a + b == b + a)
Sadly, it is not associative (i.e. (a+b)+c != a+(b+c))
Imagine a being a large number, and b and c being so small that adding each single one to a will result in a, but adding their sum will result in just the smallest increment over a.
- kbenson 9y agoActually, floating point addition isn't necessarily commutative[1][2], which is one of the problems of thinking of floating point as just a number. Although in this case, it's at least still addition, but the type of things being added have special conditions. It's more like doing calculations on scientific notation, where there are special rules for how to keep the right number of significant figures/precision after operations. Like scientific notation, you would probably convert to one form or another (even if in your head) before doing the operation, and keep note of the possible loss of precision. This is exactly the reason why adding floats to ints is something that people think should require an explicit conversion, so it's more obvious that's a point that may introduce loss of accuracy. 1: https://stackoverflow.com/questions/24442725/is-floating-point-addition-commutative-in-c https://stackoverflow.com/questions/24442725/is-floating-poi... 2: https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BinMath/addFloat.html https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BinMath/a...
- jabot 9y agoUrgh. C semantics. Well, at least that will not happen if you actually use IEEE754 _and_ if a, b, and c all have the same floating point precision _and_ there is no weird promotion/precision change going on. Now that you mention, there was this fascinating denial-of-service vulnerability in PHP which is (kind of) related... https://news.ycombinator.com/item?id=2066352 https://news.ycombinator.com/item?id=2066352 http://www.exploringbinary.com/why-volatile-fixes-the-2-2250738585072011e-308-bug/ http://www.exploringbinary.com/why-volatile-fixes-the-2-2250... EDIT: To expand on this: The following code is valid, and may print "weird": double x = f(); double y = x; if(x != 0 && y == 0) { printf("weird\n"); } ... if x is stored in a 80bit floating point register, and y is stored in memory and therefore only has 64bit