'only length-1 arrays can be converted to Python scalars'错误



我有这样的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

请帮我修理一下,谢谢!

问题是您正在使用期望Python标量的math.exp,例如:

>>> 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.expmath.exp的区别在于math.exp可以处理Python的数字(浮点数和整数),而np.exp可以处理numpy数组。在您的代码中,参数x是一个numpy数组,因此出现错误。