0

I came across an interesting quirk in Python when I tried running some floating-point arithmetic and got two different results when I used successive multiplication vs. exponentiation.

Here's the code snippet

money = 1000.0
interest_rate = 1.15

# Exponentiation
after_five_years = (money * (interest_rate ** 5)) - 500
print(after_five_years)
1511.3571874999993

# Successive multiplication
print((((((money * interest_rate) * interest_rate) * interest_rate) * interest_rate) * interest_rate) - 500)
1511.3571874999996

As you can see, the final decimal place is different between the two computations. I am guessing it has something to do with floating-point arithmetic and precision loss. My hypothesis is that the successive multiplication operation results in a lower precision than exponentiation. However, I wasn't sure how I could go about confirming this hypothesis.

rtindru
  • 5,107
  • 9
  • 41
  • 59
  • 1
    Short version: Yes, floating point violates normal math expectations. The same work, done in different ways or different (but logically equivalent) orders can come up with different results, due to rounding of intermediate results. If you need math that follows stricter rules, use the `fractions` or `decimal` modules. – ShadowRanger Aug 13 '21 at 00:55
  • 1
    Just for fun, try: `money * (interest_rate * interest_rate) * (interest_rate * interest_rate * interest_rate) - 500` which still uses multiplication, just in a different order. You'll get yet another result. While `money * (interest_rate * interest_rate * interest_rate * interest_rate) * interest_rate - 500` will match your exponentiation case. Floating point is the Devil, plain and simple. – ShadowRanger Aug 13 '21 at 01:05

0 Answers0