0

Can someone explain this?

Input:

58/100*100

Result:

57.99999999999999

Yet...

Input:

26/100*100

Result:

26.0

Also, how can I consistently get results like in the second case?

Asclepius
  • 57,944
  • 17
  • 167
  • 143
Dance Party2
  • 7,214
  • 17
  • 59
  • 106
  • It is not a Python error. That is how Floating-point arithmetic works. – Punit Gupta Aug 25 '17 at 16:14
  • Read about [Python floating-point inaccuracies](https://docs.python.org/2/tutorial/floatingpoint.html). – Mangohero1 Aug 25 '17 at 16:15
  • 1
    This issue is inherent to binary floating-point calculations. Try the `Decimal` module, which lets you do the math in decimal, isn't subject to these, but is slower. – kindall Aug 25 '17 at 16:15
  • Why do you care really? Please explain so we can address the real issue. – Asclepius Aug 25 '17 at 16:18
  • What Every Computer Scientist Should Know About Floating-Point Arithmetic http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Daniel F Aug 25 '17 at 16:19
  • I'm not convinced the duplicate is the whole story. The point I make is that the python bods changed the behaviour in version 3. Bad folk indeed! – Bathsheba Aug 25 '17 at 16:19
  • @kindall: Decimal is also subject to floating-point rounding error; the error just happens in more intuitive places, because the display base and the representation base are the same, and because humans are trained to think in decimal. – user2357112 Aug 25 '17 at 16:26
  • @Bathsheba: I don't think the behavior change is important to mention. It doesn't sound like the questioner was expecting 0 for either answer. – user2357112 Aug 25 '17 at 16:27

1 Answers1

2

This is all due to floating point arithmetic and a subtle change in the way python evaluates expressions containing numeric literals.

Since python 3, your expressions above will be calculated in floating point; before then integer arithmetic would have be used.

In IEEE754 floating point, 0.58 is further away from the true value than 0.26. That's enough to throw off the heuristics that your output formatter is using.

Performing the multiplication before the division can help in some circumstances, and will do here as the product can be represented exactly.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483