-2

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?

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
Alexander Soare
  • 2,825
  • 3
  • 25
  • 53
  • 2
    Read [Floating Point Arithmetic: Issues and Limitations](https://docs.python.org/2/tutorial/floatingpoint.html) – Mazdak Aug 01 '15 at 10:26

2 Answers2

3

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
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
1

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?

Community
  • 1
  • 1
Håken Lid
  • 22,318
  • 9
  • 52
  • 67