-1

Edit: I am aware this question was already answered, I just didn't find it. Thanks to everyone who pointed me in the right direction.

Why is it that when I run the following code the answers are not 0?

a = .1
d = .3

x = - a - a - a + d
y = a + a + a - d

print(f'x is {x}')
print(f'x is {y}')

In other words -.1 - .1 - .1 + .3 and .1 + .1 + .1 - .3

Instead I get the following:

x is -5.551115123125783e-17
y is 5.551115123125783e-17

It's almost zero but it isn't zero.

Is this due to how the python language works, is it a hardware thing, or something else?

I can't seem to find anything on stack overflow concerning this and would really like to understand what is going on.

Alex Lussier
  • 113
  • 1
  • 9

2 Answers2

3

See this article: David Goldberg - What Every Computer Scientist Should Know About Floating-Point Arithmetic

Essentially, this is a well known issue with floating point arithmetic. You could use the round function, and round to a very small digit for practical precision.

round(-5.551115123125783e-17, 10) will still return 0, which is what you want.

joelhed
  • 60
  • 6
Rohan Singh
  • 461
  • 2
  • 5
  • 20
0

This is due to the way most programming languages store floating point numbers, where .1 + .1 + .3 would equal 0.30000000000000004.

Instead of checking if it's 0, try just checking if the absolute value of the different between them is smaller than a certain number:

abs((.1+.1+.3)-.3) < 0.0001

zbys
  • 453
  • 2
  • 8