在给定一组数据点的情况下拟合积分函数

问题描述 投票:0回答:1

我具有在不同厚度下测量给定材料电阻率的度量,我必须使用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,则代码会运行。如何修改我的代码使其起作用?

python curve-fitting
1个回答
0
投票

看看这个

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.
© www.soinside.com 2019 - 2024. All rights reserved.