-2

I was trying to do the follow calculation in python 3:

https://i.stack.imgur.com/f5y7z.png

add with:

https://i.stack.imgur.com/Txoya.png

that should return 0 (images were made in wolframalpha).

When I try to do the same calculation in python:

pow((2*3*5),28)-29*math.floor(pow((2*3*5),28)/29)-1

it returns 4303955653455607115022335.

the value of each part is:

228767924549610000000000000000000000000000 correct.

-228767924549609995696044346544392884977665 incorrect.

How can I fix this?

zamir
  • 2,144
  • 1
  • 11
  • 23
aesthetic
  • 41
  • 1
  • 5
  • 1
    Please include all the relevant code and information as **text** in the question itself, not as external images. – Thierry Lathuille Jan 12 '20 at 19:03
  • 1
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Peter Wood Jan 12 '20 at 19:06
  • You can fix this by using an actual [tag:bignum] library or [the `fractions` module](https://docs.python.org/3.8/library/fractions.html) – ForceBru Jan 12 '20 at 19:12

1 Answers1

0

You are using floating point division / which has a limited precision, so your large result gets rounded.

Instead, you can get what you want with integer, floor division //, which has an integer result with unlimited precision:

import math
pow((2*3*5),28)-29*(pow((2*3*5),28)//29)-1
# 0
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50