首页 > 解决方案 > 给定一组数据点拟合积分函数

问题描述

我测量了在不同厚度下测量的给定材料的电阻率,我必须使用 Fuchs-Sondheimer 模型拟合这些点。我以这种方式定义了拟合函数:

def ff(x, aa, p):
    return aa/(1-(3/(2*x))*integrate.quad(lambda t: (1/t**3 - 1/t**5)*(1-numpy.exp(-x*t))/(1-p*numpy.exp(-x*t)), 1, 1000))

其中 t 是积分变量,x 是材料的厚度,所以它是自变量,而 aa 和 p 是两个拟合参数。当我运行代码时,它在积分定义中给我一个错误:

TypeError: only size-1 arrays can be converted to Python scalars

我想错误的原因是 x 和 p 出现在积分函数以及积分变量 t 中,所以它说我正在尝试将向量传递给积分。实际上,如果我尝试从积分中消除 x 和 p ,代码就会运行。如何修改我的代码以使其正常工作?

标签: pythoncurve-fitting

解决方案


看看这个

import numpy as np
from scipy.integrate import quad

def ff( x, aa ):
    return aa * quad( lambda t: t - x * t**2, 0, 1 )

def ff_select( x, aa ):
    return aa * quad(lambda t: t - x * t**2, 0, 1 )[0]

def ff_iter( x, aa ):
    if isinstance( x, (list, tuple, np.ndarray )):
        out = np.fromiter( ( ff_iter( y, aa ) for y in x ), np.float )
    else:
        out = aa * quad( lambda t: t - x * t**2, 0, 1 )[0]
    return out


print "this works, but is not desired"
print ff( 5 , 3 )

try:
    print ff( 5 , 3.1 )
except TypeError:
    print "\nquad returns a tuple. Select the result by picking the first element."

print "\nthis works"
print ff_select( 5 , 3.1 )
print "but still can't handle lists"
xx = np.linspace( 0, 1, 10 )
print
try:
    print ff_select( xx , 3 )
except TypeError:
    print "quad has problems with lists. Make the iteration external."

print"\nUsing this function definition should work in all reasonable cases"
print ff_iter( 5.1, 3.1 )
print ff_iter( xx, 3.1 )
print ff_iter( ( 1, 1.1, 2.1), 3.1 )
print ff_iter( [ 1, 1.1, 2.1 ], 3.1 )
## one may think about extending the code such that the output type 
## matches the input.Right now it is always an ndarray.

推荐阅读