0

When I divide 1/5e-5 it gives the correct answer but 1/5e-6 gives an answer close to the correct one.

>>> 1/5e-5
20000.0
>>> 1/5e-6
199999.99999999997 (should be 200000)
>>>

How can I get it to show the exact value. I tried importing decimel, numpy and scipy but none of them change the result.

mhlester
  • 22,781
  • 10
  • 52
  • 75
Alvi Newaz
  • 11
  • 2
  • https://docs.python.org/3.1/tutorial/floatingpoint.html – Mark Ransom Jan 27 '16 at 22:46
  • 1
    You should read up on [floating point rounding error](http://programmers.stackexchange.com/questions/101163/what-causes-floating-point-rounding-errors). The basic issue is that computers cannot exactly model certain decimal fractions in binary, much like we cannot model 2/3 (0.66667...) in decimal. – Nick White Jan 27 '16 at 22:46
  • You can't always get an "exact value" with floating-point math. – TigerhawkT3 Jan 27 '16 at 22:47
  • Could you make use of the [fractions](https://docs.python.org/2/library/fractions.html) module? – jacob Jan 27 '16 at 22:47
  • To get python to round the number to some level of precision, try [round(1/5e-6)](https://docs.python.org/2/library/functions.html#round) – Nick White Jan 27 '16 at 22:48
  • I'm not sure that this is an exact dupe -- OP seems to be at least a little aware of the limitations of floating point mathematics (based on the attempts to use `decimal`, `scipy`, `numpy`, ...). The question is if there is any way to work-around the limitations of floating point math to get an exact answer. It seems to me that it should be possible with decimal or fractions . . . – mgilson Jan 27 '16 at 22:51
  • @NickWhite rounding doesn't help, because most perfectly exact decimals simply can't be represented in binary. You can round it 100 times but you still get the same almost-but-not-quite answer. – Mark Ransom Jan 27 '16 at 23:33

1 Answers1

2

You can get decimal to do this properly -- You just have to avoid using floating point numbers along the way:

>>> import decimal
>>> decimal.Decimal('1') / (decimal.Decimal('5') / decimal.Decimal('1000000'))
Decimal('2E+5')
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • You can use floating point numbers converted to `Decimal`, as long as they're exact. Integers converted to floating point will meet this requirement as long as they're less than `2**53`. – Mark Ransom Jan 27 '16 at 23:35