简体   繁体   English

float64到float32转换会产生意外结果

[英]float64 to float32 conversion gives unexpected result

When I convert a float64 number to a float32 number I get a weird result: 当我将float64数转换为float32数时,我得到一个奇怪的结果:

In [22]: np.float32(20140131.0)
Out[22]: 20140132.0

Why is this happening? 为什么会这样?

20140131.0 can't be represented as a 32 bit integer. 20140131.0不能表示为32位整数。

32 bit float 32位浮点数

64 bit float 64位浮点数

With floats, within each range, the numbers are evenly spaced. 对于浮动,在每个范围内,数字均匀分布。

So it's (1+M) * 2^(E) 所以它是(1 + M)* 2 ^(E)

so 20140131.0 is in the range of 2^24 to 2^25. 所以20140131.0在2 ^ 24到2 ^ 25的范围内。 There are 16,777,216 numbers in that range, but only 8,388,608 representable floats. 该范围内有16,777,216个数字,但只有8,388,608个可表示的浮点数。 So you can only represent even numbers. 所以你只能代表偶数。

Since in 32bit floats, there are only 23 bits for the mantissa, integers can only be represented up to 2^24. 由于在32位浮点数中,尾数只有23位,因此整数最多只能表示为2 ^ 24。 Above that, epsilon > 1 . 在此之上, epsilon > 1 Where epsilon is the difference between two adjacent floating point numbers. 其中epsilon是两个相邻浮点数之间的差异。

As for python floats, i believe they work like this: 至于python浮动,我相信他们的工作方式如下:

Floats in python are typically not 32 bit, or 64 bit, so this isn't a problem. python中的浮点数通常不是32位或64位,所以这不是问题。 The length is adjusted automatically. 长度自动调整。 Buy you're casting them to specific types, so you see the lack of resolution. 买你把它们投射到特定的类型,所以你看到缺乏分辨率。 With 64bit integers, there are 52 bits in the mantissa, so you will not see this problem until you go above 2^53. 对于64位整数,尾数中有52位,所以在超过2 ^ 53之前你不会看到这个问题。

Also, the way the number is rounded to the nearest float is normally defined in a system wide manner (i think), but python's casting may over rule this, i'm not completely familiar with it. 此外,数字舍入到最近的浮点数的方式通常以系统范围的方式定义(我认为),但是python的转换可能超过此规则,我并不完全熟悉它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM