给定一组数据点拟合积分函数

2024-07-07 07:58:45 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 方法函数代码模型numpyreturn定义def
1条回答
网友
1楼 · 发布于 2024-07-07 07:58:45

看看这个

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.

相关问题 更多 >