【问题标题】:Two differents values when evaluating a numpy array评估 numpy 数组时的两个不同值
【发布时间】:2021-12-30 21:17:24
【问题描述】:

我有一个非常基本的问题。

import numpy as np

def u(x):
    return 1 - x + x**2 - x**3 + x**4 - x**5 + x**6 - x**7 + x**8 - x**9 + x**10

X = np.array([8, 9])
Y = u(X)
print("u(8) = ", u(X)[0], "or", u(8))
print("u(9) = ", u(X)[1], "or", u(9))

我创建了一个包含 8 和 9 的数组,然后将函数“u”应用到这个数组。但由于某种原因 u(X)[1] != u(9) (即使 X[1] == 9):

u(8) =  954437177 or 954437177
u(9) =  -1156861335 or 3138105961

奇怪的是,对于 n

【问题讨论】:

    标签: python arrays numpy evaluation


    【解决方案1】:

    Numpy 在内部不使用 Python 任意精度数字类型,而是(通常)使用机器数字。在这种情况下,您创建的数组 X 自动将 32 位整数作为其类型。对于那些,你的函数溢出了。我无法在 Python 中轻松演示这一点,但在 Julia 中也有同样的效果:

    julia> u(Int32(9))
    -1156861335
    
    julia> u(Int32(8))
    954437177
    
    julia> u(Int64(9))
    3138105961
    
    julia> u(Int64(8))
    954437177
    
    julia> typemax(Int32)
    2147483647
    

    解决办法是明确告诉np.array你想使用什么类型:

    In [2]: X = np.array([8, 9], dtype=float)
    
    In [4]: u(X)
    Out[4]: array([9.54437177e+08, 3.13810596e+09])
    
    In [5]: X = np.array([8, 9], dtype=np.int64)
    
    In [6]: u(X)
    Out[6]: array([ 954437177, 3138105961])
    
    # you can use Python integers, but it's going to lose efficiency!
    In [8]: X = np.array([8, 9], dtype=object)
    
    In [9]: u(X)
    Out[9]: array([954437177, 3138105961], dtype=object)
    
    # for comparison
    In [22]: X = np.array([8, 9], dtype=np.int32)
    
    In [25]: u(X)
    Out[25]: array([  954437177, -1156861335], dtype=int32)
    

    【讨论】:

    • 您可以通过dtype=np.int32获得OPs结果。
    • @PresidentJamesK.Polk 是的,但这确实是他们已经拥有的。我想展示的是u(np.int32(9))——但令我惊讶的是,它并没有溢出。
    • type(np.int32(2147483647) + 1)np.int64... 很高兴知道。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 2014-08-01
    • 1970-01-01
    相关资源
    最近更新 更多