For some reason, Python is giving me incorrect results when subtracting certain floats such as 4.35-8.55
or 5.945-9.465
. These are interpreted as -4.200000000000001
and -3.5199999999999996
, respectively. It is obvious that the results should be -4.2
and `-3.521, as I get with other calculators. This is bewildering--why am I getting a truncated repeating decimal for non-repeating rational numbers? Does anyone else get these same results?
Asked
Active
Viewed 37 times
0

Neithan
- 395
- 1
- 4
- 9
-
I guess I won't be using Python for a calculator anymore... – Neithan Jul 26 '16 at 04:09
-
1_"I guess I won't be using Python for a calculator anymore"_ Clearly you haven't read the first answer in that topic. – Aran-Fey Jul 26 '16 at 04:17
-
@AllanBurleson if you need arbitrary precision, you need to use the [decimal](https://docs.python.org/3/library/decimal.html) library. It's amazing to me how often this comes up, because this should be common knowledge to any programmer that *binary* floating point will always have problems representing *decimals.* – juanpa.arrivillaga Jul 26 '16 at 04:22
-
Go ahead and open your browsers dev tools and open the console tab and enter `.1 + .2` and see what answer you get OP. – kylieCatt Jul 26 '16 at 05:06
-
@Rawing It hadn't been marked as a duplicate yet. – Neithan Jul 26 '16 at 05:09
-
@juanpa.arrivillaga I'm fairly new to programming; I didn't know that. – Neithan Jul 26 '16 at 05:11