How To Correctly Add Floating Numbers In Python?
I am trying to add 0.2 value to constant x where x = 8 in a loop that runs to 100. Following is the code x = 8 >>> for i in range(100): ... x += 0.2 ... >>>
Solution 1:
You can use double-precision floating point, sure. You're already using it by default.
As for a way around it:
x += 0.2 * 100
I know that sounds facile, but the solution to floating point imprecision is not setting FLOATING_POINT_IMPRECISION = False
. This is a fundamental limitation of the representation, and has no general solution, only specific ones (and patterns which apply to groups of specific situations).
There's also a rational number type which can exactly store 0.2
, but it's not worth considering for most real-world use cases.
Post a Comment for "How To Correctly Add Floating Numbers In Python?"