0

I'm getting weird results in Python with a very simple operation. In my case, I'm making a funny terminal game to practice operations with fractions, and the game works fine until Python returns too much decimals. For example:

res1 =(3/4)-(6/5)
res2 = -9/20
print(res1)
print(res2)

If you operate (3/4) - (6/5) you get the result of -9/20 (in fraction). So both operations should return the same result, in decimals. However, as you can see, I get the following results:

res1 = -0.44999999999999996
res2 = -0.45

At the moment I'm using the function round() with 2 decimals. However, I would like to know if there's a better way to fix this.

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
Unix
  • 1,358
  • 3
  • 14
  • 23
  • For precise math with fractions/decimals, use the builtin [`decimal`](https://docs.python.org/3/library/decimal.html) module – Samathingamajig Apr 10 '23 at 03:39
  • 1
    If you want to do fraction math, use [`fractions.Fraction`](https://docs.python.org/3/library/fractions.html). (*Not* `decimal`. That's for decimal math.) – user2357112 Apr 10 '23 at 03:42

0 Answers0