使用scipy.integrate.quad和nquad集成数组“不返回有效的float”

时间:2015-07-29 19:23:51

标签: arrays python-2.7 numpy quad

我想绘制一个带数字的函数,将其用作集成中的参数,并返回集成的结果。 当我输入一个浮点数时,函数返回值就好了。但是当我给它类似于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()

0 个答案:

没有答案