Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
1
>>> 295147905179352825855.0 % 2
0.0
>>> format(295147905179352825855.0, '.20f')
'295147905179352825856.00000000000000000000'
>>> 295147905179352825856.0 == 295147905179352825855.0
True
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading