Update: Thanks guys, I didn’t realize it was very close to zero but not exactly zero. Is there a way around it so my program sees it as a zero? Its throwing my results off because this value is not being picked up as a zero.
Update2: figured it out, adding:
from decimal import *
getcontext().prec = 6
and then Decimal(number) fixed it.Thanks everyone!
I am running a simple piece of code but was getting a weird result with a specific number. Its a bit strange because when I run the same command in the python terminal I get the result I expect.
I made the print statement, the command its running so I could copy/paste it in the interpreter(python 2.7) to see if the results are the same. Here’s the program:
x = 20
for s in range(100 + 1):
for c in range(100+1):
if s == 7:
print s, '-', (c*0.01), '*', x, ' = ', (s - (c*0.01) * x)
The results look fine except one:
7 - 0.33 * 20 = 0.4
7 - 0.34 * 20 = 0.2
7 - 0.35 * 20 = -8.881784197e-16
7 - 0.36 * 20 = -0.2
7 - 0.37 * 20 = -0.4
When I copy/paste 7 - 0.35 * 20 into the interpreter I get 0.0 which is what I would expect(the other results in the program seem fine, except 7 – 0.35 * 20 and(not shown) a similar value with 14.
I’m a bit stumped, I’m not what’s going on here.
There is no difference between the output of the interactive interpreter and your program, but you’re giving it different input. Observe:
And that, as others have already noted, is due to roundoff error.