TypeError:使用trapz方法时,只能将大小为1的数组转换为Python标量
这是我的python代码TypeError:使用trapz方法时,只能将大小为1的数组转换为Python标量,python,numpy,typeerror,integration,quad,Python,Numpy,Typeerror,Integration,Quad,这是我的python代码 import numpy as np from scipy.integrate import quad, trapz, simps import math def f(x): return math.exp(-(x**2/2))/math.sqrt(2*math.pi) result, error = quad(f, 0, np.inf) print("{:f} {:g}".format(result, error)) x = np.a
import numpy as np
from scipy.integrate import quad, trapz, simps
import math
def f(x):
return math.exp(-(x**2/2))/math.sqrt(2*math.pi)
result, error = quad(f, 0, np.inf)
print("{:f} {:g}".format(result, error))
x = np.arange(0, 99999, 0.001)
fun = f(x)
res1 = trapz(fun, x)
print(res1)
我得到了这个错误:
... line 6, in f
return math.exp(-(x**2/2))/math.sqrt(2*math.pi)
TypeError: only size-1 arrays can be converted to Python scalars
为什么会这样?
使用quad方法进行集成效果很好,但与trapz方法不兼容。正如用户所评论的,您只能使用带有标量值的数学函数,对于数组,您必须使用NumPy库中提供的数学函数。
数学
函数只能使用标量值,而不能使用数组。如果x
是一个数组,请使用np.exp(x)
。@hpaulj它起作用了。谢谢