Check if Large Float is Even or Odd

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?

>Solution :

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 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
>>> 295147905179352825855.0 % 2
>>> format(295147905179352825855.0, '.20f')
>>> 295147905179352825856.0 == 295147905179352825855.0

Leave a Reply