我有這樣的 Python 代碼
import numpy as np
import matplotlib.pyplot as plt
import math
from scipy import optimize as opt
def func1(x):
f1 = math.exp(x-2) x**3-x
return f1
solv1_bisect = opt.bisect(func1, -1.5, 1.5)
x1 = np.linspace(-1.5,1.5)
y1 = func1(x1)
plt.plot(x1,y1,'r-')
plt.grid()
print('solv1_bisect = ', solv1_bisect)
我收到了錯誤訊息,例如
TypeError: only length-1 arrays can be converted to Python scalars
請幫我修復它,謝謝!
uj5u.com熱心網友回復:
問題是您使用的math.exp是需要 Python 標量的,例如:
>>> import numpy as np
>>> import math
>>> math.exp(np.arange(3))
Traceback (most recent call last):
File "path", line 3331, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-10-3ac3b9478cd5>", line 1, in <module>
math.exp(np.arange(3))
TypeError: only size-1 arrays can be converted to Python scalars
使用np.exp來代替:
def func1(x):
f1 = np.exp(x - 2) x ** 3 - x
return f1
np.exp和之間的區別在于,math.exp它math.exp適用于 Python 的數字(浮點數和整數),同時np.exp適用于 numpy 陣列。在您的代碼中,引數x是一個 numpy 陣列,因此是錯誤的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/325921.html
下一篇:改變陣列的維度
