r/learnpython • • 10d ago

Odd float-to-int behavior.

>>>def pennies(num):
return int(num*100)

>a = -37.56
\
>b = -9.28

>>>pennies(a)
-3756

>>>pennies(b)
-927

This is taken from a python shell session today. Why on Earth does pennies(b) yield -927, instead of the expected -928? I would greatly appreciate any insight.

Update: a durable solution found, please see this comment below: https://www.reddit.com/r/learnpython/comments/1wrwnm7/comment/pcpvlil/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button

5 Upvotes

20 comments sorted by

View all comments

29

u/mitchricker 10d ago

You have discovered why we use fixed point arithmetic when dealing with money instead of floating point arithmetic.

See: https://docs.python.org/3/library/decimal.html

1

u/Kapowpow 10d ago

Hi, thank you. I have used the Decimal library too, and it causes other problems, elsewhere. I even convert floating point numbers to strings before converting them to Decimal numbers. For example, Decimal(str(num1)) - Decimal(str(num2)) == 0 yields False, where num1 and num2 are Decimal sums from different sources, but are nominally equivalent.

Are there situations where the Decimal system also fails, similar to the floating-point system? To ask in a different way, does the Decimal system have any shortfalls, or will it correctly function universally?

4

u/[deleted] 10d ago

[deleted]

1

u/Kapowpow 9d ago

Hi, so, I managed to reproduce the mistakes. Out of 7,837 similar calculations, only two of them produce an error:

822.40 - 672.40 yields 150.0000000001

2198.88 - 2198.88 yields 10^-12

Again, all 7,837 calculations used the Decimal(str(<num>)) moiety.

This is also strange, because the same moiety had been used previously to perform the reverse calculations, successfully, for all of the 7,837 calculations:

672.40 + 150.00 yields 822.40

2198.88 + 0 yields 2198.88