gpt4 book ai didi

python - numexpr 中的自动 float32 提升

转载 作者:太空宇宙 更新时间:2023-11-03 19:17:30 24 4
gpt4 key购买 nike

考虑以下 dtype float32 的 NumPy 数组:

In [29]: x = numpy.arange(10, dtype=numpy.float32)

当我使用pytables.Expr将其乘以2时,我得到一个float32数组:

In [30]: tables.Expr('x * 2').eval().dtype
Out[30]: dtype('float32')

然而,当我将其乘以 2.0 时,我得到一个 float64 数组:

In [31]: tables.Expr('x * 2.0').eval().dtype
Out[31]: dtype('float64')

是否有任何方法可以在上述表达式中指定浮点文字,并且不会导致结果提升为float64

更一般地说,我有一个使用 float32 数组的表达式,并且我想确保结果也是 float32 类型(我不介意 float64 用于中间计算,但我无法将结果存储为 float64)。我该怎么做?

最佳答案

我非常确定 pytables.Expr 是基于 Numexpr 的。 Numexpr 的文档指出了有关表达式中提升的以下内容:

In operations implying a scalar and an array, the normal rules of casting are used in Numexpr, in contrast with NumPy, where array types takes priority. For example, if 'a' is an array of type float32 and 'b' is an scalar of type float64 (or Python float type, which is equivalent), then 'a*b' returns a float64 in Numexpr, but a float32 in NumPy (i.e. array operands take priority in determining the result type). If you need to keep the result a float32, be sure you use a float32 scalar too.

所以这可能就是正在发生的事情。浮点常量负责提升为 64 位 float ,解决方案是显式指定浮点常量为 float32。

关于python - numexpr 中的自动 float32 提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10905272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com