1

i have a problem when calculating floating point in python, here is an example:

import numpy
print numpy.floor(3*1.4+2*1.4)
>> 6.0

it return 6.0 while i am excepting 7.0

i can fix this simply by

print(numpy.floor( (3*100*1.4*100 + 2*100*1.4*100) / 10000 ))
>> 7.0

but seems its not a very good practices, i have google for a while and try a different type of numpy.float, Decimal, int etc. The problem is still persist. Does anyone have any idea better than this?

Chris
  • 47
  • 6
  • Not sure I understood the question but did you try `numpy.round` ? – Mohamed AL ANI May 30 '18 at 10:34
  • 2
    fyi: https://docs.python.org/3/tutorial/floatingpoint.html – Jonas May 30 '18 at 10:35
  • 2
    See also: [Is floating point math broken?](https://stackoverflow.com/q/588004/253056) – Paul R May 30 '18 at 10:36
  • 3
    1.4 can't be expressed exactly as a binary floating-point number. After conversion back to decimal it looks like 1.399999999999999911182158029987476766109466552734375, so your result is less than 7. – PM 2Ring May 30 '18 at 10:38
  • The `decimal` module works, but you need to pass it the numbers as strings. If you pass it floats the damage has already been done. `from decimal import Decimal` `a = Decimal('1.4'); print(3*a + 2*a)` print `7.0`, as expected. – PM 2Ring May 30 '18 at 10:42

0 Answers0