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 ,代码就会运行。如何修改我的代码以使其正常工作?
解决方案
看看这个
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.
推荐阅读
- bash - kubernetes 作业不会终止
- python - 为什么我在 docker 和 postgresql 之间存在连接问题?
- swift - 使用 CoreGraphics 绘制动态饼图段
- r - 当值低于零时如何使线变为红色,高于零时如何使线变为绿色?
- c# - 从“B”或“C”调用的方法“A”(MethodBase/MethodInfo)获取调用堆栈,而不使用堆栈跟踪
- c++ - GMP 卡在生成相同的随机整数
- python - ValueError:期望 x 为非空数组或数据集。(Colab 上的 Tensor Flow DNN 模型)
- java - 如何阻止 IntelliJ 在 Java 中自动导入 org.jetbrains.annotations?
- flutter - Flutter customPainter不会重新绘制
- reactjs - 如何在 daypicker 时刻反应中对齐占位符中的文本?