Here is my input
import numpy as np
array = [0.29, 0.59, 0.12]
na_array = np.array(array)
a = np.sum([0.29, 0.59, 0.12])
print a
if (a == 1.0):
print "success"
the output is:
1.0
Why isn't "success" printed?
Here is my input
import numpy as np
array = [0.29, 0.59, 0.12]
na_array = np.array(array)
a = np.sum([0.29, 0.59, 0.12])
print a
if (a == 1.0):
print "success"
the output is:
1.0
Why isn't "success" printed?
Its just rounding off when printing, the actual value of a
is - 0.99999999999999989
(This is because of internal floating point representations).
Example -
In [13]: a = np.sum([0.29, 0.59, 0.12])
In [14]: a
Out[14]: 0.99999999999999989
In [15]: print a
1.0
This happens because -
In [20]: 0.29 + 0.59
Out[20]: 0.8799999999999999
If this is a real issue, you can try rounding the number before comparing -
In [22]: if round(a,1) == 1.0:
....: print('success')
....:
success
Because the floats are not equal. Using ==
with floating point numbers is usually not a good idea.
What is the best way to compare floats for almost-equality in Python?