简体   繁体   English

Python float 和 numpy float32 的区别

[英]Difference between Python float and numpy float32

What is the difference between the built in float and numpy.float32 ?内置的floatnumpy.float32什么区别?

Example例子

a = 58682.7578125
print type(a)
print a
print type(numpy.float32(a))
print numpy.float32(a)

Output: Output:

<type 'float'>
58682.7578125
<type 'numpy.float32'>
58682.8

I've found here that numpy.float32 is:我在这里发现numpy.float32是:

float32 Single precision float: sign bit, 8 bits exponent, 23 bits mantissa float32 单精度浮点数:符号位,8位指数,23位尾数

didn't find what the built in float format is.没有找到内置的float格式是什么。

Python's standard float type is a C double : http://docs.python.org/2/library/stdtypes.html#typesnumeric Python的标准float类型是C doublehttp//docs.python.org/2/library/stdtypes.html#typesnumeric

NumPy's standard numpy.float is the same, and is also the same as numpy.float64 . NumPy的标准numpy.float是相同的,也和numpy.float64

Data type-wise numpy floats and built-in Python floats are the same, however boolean operations on numpy floats return np.bool_ objects, which always return False for val is True .数据类型方面的 numpy 浮点数和内置的 Python 浮点数是相同的,但是 boolean 对 numpy 浮点数的操作返回np.bool_对象,对于val is True总是返回False Example below:示例如下:

In [1]: import numpy as np
   ...: an_np_float = np.float32(0.3)
   ...: a_normal_float = 0.3
   ...: print(a_normal_float, an_np_float)
   ...: print(type(a_normal_float), type(an_np_float))

0.3 0.3
<class 'float'> <class 'numpy.float32'>

Numpy floats can arise from scalar output of array operations. Numpy 浮点数可以从数组运算的标量 output 中产生。 If you weren't checking the data type, it is easy to confuse numpy floats for native floats.如果您不检查数据类型,很容易将 numpy 浮点数与本机浮点数混淆。

In [2]: criterion_fn = lambda x: x <= 0.5
   ...: criterion_fn(a_normal_float), criterion_fn(an_np_float)

Out[2]: (True, True)

Even boolean operations look correct.甚至 boolean 操作看起来都是正确的。 However the result of the numpy float isn't a native boolean datatype, and thus can't be truthy.但是 numpy 浮点数的结果不是本机 boolean 数据类型,因此不可能为真。


In [3]: criterion_fn(a_normal_float) is True, criterion_fn(an_np_float) is True
Out[3]: (True, False)

In [4]: type(criterion_fn(a_normal_float)), type(criterion_fn(an_np_float))
Out[4]: (bool, numpy.bool_)

According to this github thread , criterion_fn(an_np_float) == True will evaluate properly, but that goes against the PEP8 style guide.根据这个 github threadcriterion_fn(an_np_float) == True将正确评估,但这违反了 PEP8 风格指南。

Instead, extract the native float from the result of numpy operations.相反,从 numpy 操作的结果中提取本机浮点数。 You can do an_np_float.item() to do it explicitly (ref: this SO post ) or simply pass values through float() .您可以执行an_np_float.item()来显式执行此操作(参考: this SO post )或简单地通过float()传递值。

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

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