1

i am facing this problem in python below is the code in python

>>> p=350.
>>> p-=0.1
>>> p-=0.1
>>> print p-349.8
-5.68434188608e-14
>>> 

i have checked this program many times and i think the output of print p-349.8 should have come 0. i have also tried this in other languages too in c++ , Java and python and i want output to come 0.0 please help

Sufian Latif
  • 13,086
  • 3
  • 33
  • 70
  • 4
    http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – William Pursell Apr 29 '14 at 12:25
  • Floating point is the same everywhere. However, your particular interaction would result in `0.0` in e.g. Lisp or Racket, because they treat literals such as `0.1` exactly (i.e. not as floating point) unless you tell them otherwise. – molbdnilo Apr 29 '14 at 12:31

1 Answers1

0

Yes, all programming languages deal in base-2 numbers and therefore it is difficult to accurately express a floating point number as a base-10.

You could perhaps use the Decimal Class

sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • An alternative - if you know in advance how many decimal places you are going to be using (e.g. in financial applications) - is to multiply out the decimal places and do the Math with Ints. e.g. in finance work in pennies as opposed to pounds. – NDevox Apr 29 '14 at 12:29
  • Some (admittedly obscure) language use rationals or decimal floating point by default. Those don't exhibit these specific errors (though they have other limitations). –  Apr 29 '14 at 12:30