How can floating point calculations be made deterministic?

后端 未结 6 765
执念已碎
执念已碎 2020-12-03 21:21

Floating point calculation is neither associative nor distributive on processors. So,

(a + b) + c is not equal to a + (b + c)

and <

6条回答
  •  醉酒成梦
    2020-12-03 21:38

    Even using a high-precision fixed point datatype would not solve the problem of making the results for said equations determinisic (except in certain cases). As Keith Tomposon pointed out in a comment, 1/3 is a trivial counter-example of a value that cannot be stored correctly in either a standard base-10 or base-2 floating point representation (regardless of precision or memory used).

    One solution that, depending upon particular needs, may address this issue (it still has limits) is to use a Rational number data-type (one that stores both a numerator and denominator). Keith suggested GMP as one such library:

    GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers. There is no practical limit to the precision...

    Whether it is suitable (or adequate) for this task is another story...

    Happy coding.

提交回复
热议问题