我被要求在 python3 中計算一個數字的立方根并使用以下代碼:
import numpy as np # numerical routines
def myfunct(x):
return np.power(x,3./2.)
xStar = 4
print('Exact value at',xStar,' is in myfunc ',myfunct(xStar))
這很好,但是我偶然發現了以下作品
import numpy as np # numerical routines
def myfunct(x):
return np.power(x,3./2.)
def anotherfunct(x):
return pow(x,3./2.)
xStar = 4
print('value at',xStar,' is in myfunc',myfunct(xStar))
print('value at',xStar,' is in anotherfunc',anotherfunct(xStar))
N = 3
xpt = np.linspace( 8., 12., num=N )
print(xpt)
print(myfunct(xpt))
print(wrongfunct(xpt))
這似乎給出了相同的答案,即
[ 8. 9.5 11. ]
[22.627417 29.28096651 36.48287269]
[22.627417 29.28096651 36.48287269]
我的問題是, pow() 是否真的與 np.power() 相同,如果是這樣,在數值編程中使用 pow() 而不是 np.power() 是否會被認為是不好的編程習慣?
uj5u.com熱心網友回復:
prehaps看一下兩者的檔案:
- 內置 pow
引數必須具有數字型別。對于混合運算元型別,適用二元算術運算子的強制規則。
- np.power
將 x1 中的每個堿基提高到 x2 中的位置對應冪。x1 和 x2 必須可廣播到相同的形狀。
主要區別 - 與大多數 numpy 函式相比,內置函式 - 僅在您查看輸入值的型別時才相關。如果您只希望使用單值輸入(僅針對單個數字計算它),那么它們的行為將相同,如果您想立即對一組輸入進行計算,內置pow將對此不滿意。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/530645.html
