The Python Oracle

Error in astype float32 vs float64 for integer

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Thinking It Over

--

Chapters
00:00 Error In Astype Float32 Vs Float64 For Integer
00:20 Accepted Answer Score 4
01:01 Answer 2 Score 3
01:18 Thank you

--

Full question
https://stackoverflow.com/questions/1986...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python27 #numpy #floatingpoint

#avk47



ACCEPTED ANSWER

Score 4


A 32-bit float can exactly represent about 7 decimal digits of mantissa. Your number requires more, and therefore cannot be represented exactly.

The mechanics of what happens are as follows:

A 32-bit float has a 24-bit mantissa. Your number requires 27 bits to be represented exactly, so the last three bits are getting truncated (set to zero). The three lowest bits of your number are 0112; these are getting set to 0002. Observe that 0112 is 310.




ANSWER 2

Score 3


A float32 only has 24 bits of significand precision, which is roughly seven digits (log10(2**24) = 7.22). You're expecting it to store an 8-digit number exactly, which in general is impossible.