0

I have tried using the modulo operator for small floats and it works perfectly fine. For example: 5 % 2 returns 1.

But for other large floats that are read as exponential in python it just returns 0 every time even if the number is odd. Like this:

295147905179352825855 % 2 returns 0 even though that number is clearly odd.

Is there anything I can do to check large floats without python reading it as exponential?

phuclv
  • 37,963
  • 15
  • 156
  • 475
mail_liw
  • 106
  • 1
  • 9
  • [What Every Computer Scientist Should Know About Floating-Point Arithmetic](//docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Pranav Hosangadi Jun 10 '22 at 15:14
  • 1
    When I do `295147905179352825855 % 2` I get `1`. Did you mean `295147905179352825855.0 % 2`? Converting to floating point loses precision. – Barmar Jun 10 '22 at 15:18

1 Answers1

2

What you said is not true. 295147905179352825855 % 2 should work because Python does arbitrary precision math on integers. There's no floating-point values in your question

OTOH if you use a float like 295147905179352825855.0 then it obviously won't work because on most modern platforms Python uses IEEE-754 binary64 format which has only 53 bits of precision and can't store values such as 295147905179352825855.0. The closest value is 295147905179352825856.0 which is clearly an even number

>>> 295147905179352825855 % 2
1
>>> 295147905179352825855.0 % 2
0.0
>>> format(295147905179352825855.0, '.20f')
'295147905179352825856.00000000000000000000'
>>> 295147905179352825856.0 == 295147905179352825855.0
True
phuclv
  • 37,963
  • 15
  • 156
  • 475
  • When I float the number and print it, this is the result: 2.9514790517935283e+20 – mail_liw Jun 10 '22 at 15:36
  • @user14591825 you need to print the full precision to get the actual value: `format(295147905179352825855.0, '.20f')` – phuclv Jun 10 '22 at 15:51
  • The source you cite with a [link](https://docs.python.org/3/tutorial/floatingpoint.html) does not say what your answer says, “Python uses IEEE-754 binary64 format.” It says almost all platforms map Python to IEEE-754 double precision (binary64). “Almost all” is not “all,” and bugs occur when people assume things that are not true. Cited sources should not be misstated. – Eric Postpischil Jun 10 '22 at 18:47