我想绘制一个接受数字的函数,将其用作积分中的参数,并返回积分的结果。当我输入一个浮点数时,该函数返回值就好了。但是当我给它类似 numpy.linspace(0,3,500) 的东西时,我函数中的“quad”模块反应很糟糕。
我已经查找了使用“nquad”的建议,因为它在数组上更好。此外,我已经阅读了文档并查找了错误,但没有一个示例/解决方案似乎涉及我的特殊情况。
这是我的函数,以及运行它们时出现的错误。
quad:“提供的函数没有返回有效的浮点数”
def fsum(x, dVdm, v_c, dposdmirror, gauss_width):
integrand = lambda chi: sum_rough(x, dVdm, v_c, dposdmirror) * np.exp(-(x-chi)**2 / (2 * gauss_width))
def_integral, err = nquad(integrand, 1, 2)
sum_fit = def_integral * np.sqrt(2 * np.pi * gauss_width ** 3) ** (-1)
return sum_fit
nquad:与“quad”相同的错误。这次是完整的、自我维持的代码。我使用了一个带有单个浮点数的函数。
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.integrate import quad
from scipy.integrate import nquad
abs_field = .03
resistor = 9.95
avg_current = 0.08
muMs = .64
active_thick = 10e-9
mag_thick = 10e-9
width = 50E-6
t = (active_thick + mag_thick)/2
mu_0 = 1.256e-6
gyr = 1.76e11
hbar = 1.05457e-34
fund_charge = 1.602e-19
def sum_rough(x, dVdm, v_c, dposdmirror):
sum_fit1 = (-dVdm/(muMs + abs_field)) * avg_current*mu_0 / (2 * np.pi * width)
sum_fit2 = (np.log(t**2 + .25*(width + 2*dposdmirror*(x-v_c))**2)-np.log(t**2 + .25*(width-2*dposdmirror*(x-v_c))**2))
sum_fit3 = sum_fit1 * sum_fit2
sum_fit4 = sum_fit3 * np.piecewise(x, [abs(x-v_c)*dposdmirror < width/2, abs(x-v_c)*dposdmirror >= width/2], [1, 0])
return sum_fit4
def fsum(x, dVdm, v_c, dposdmirror, gauss_width):
integrand = lambda chi: sum_rough(x, dVdm, v_c, dposdmirror) * np.exp(-(x-chi)**2 / (2 * gauss_width))
def_integral, err = nquad(integrand, [[1, 2]], args=None, opts=None)
sum_fit = def_integral * np.sqrt(2 * np.pi * gauss_width ** 3) ** (-1)
return sum_fit
dVdm = -3
v_c = 1.3
dposdmirror = 30e-6
gauss_width = 50
print fsum(1.5, dVdm, v_c, dposdmirror, gauss_width)
xlin = np.linspace(0,3,500)
ything = fsum(xlin, -3, 1.3, 30e-6, 50)
plt.plot(xlin, ything)
plt.show()