我有一個非常基本的問題。
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 < 9,我沒有這個問題。這里有什么問題?(還有我……)
uj5u.com熱心網友回復:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361250.html
