Python中函数的数学积分

3 投票
3 回答
5899 浏览
提问于 2025-04-16 12:05

我正在尝试整合这个功能:

在这里输入图片描述

但是我遇到了一个错误:

Traceback (most recent call last):

  File "<ipython console>", line 1, in <module>

  File "siestats.py", line 349, in NormalDistro

    P_inner = scipy.integrate(NDfx,-dev,dev)

TypeError: 'module' object is not callable

我的代码运行的是:

# Definition of the mathematical function:
def NDfx(x):

    return((1/math.sqrt((2*math.pi)))*(math.e**((-.5)*(x**2))))

# This Function normailizes x, u, and o2 (position of interest, mean and st dev) 
# and then calculates the probability up to position 'x'

def NormalDistro(u,o2,x):


    dev = abs((x-u)/o2)


    P_inner = scipy.integrate(NDfx,-dev,dev)

    P_outer = 1 - P_inner

    P = P_inner + P_outer/2

    return(P)

NormalDistro这个函数是用来导入的,使用方法是这样的:

foo.NormalDistro(30,2.5,1.25)

举个例子。

3 个回答

1

高斯函数的积分被称为误差函数(error function)。你可以在Python的数学库或者scipy.special中找到这个函数(如果你需要处理多个数据时,可以用它的向量化版本)。这个函数叫做erf。此外,还有一个叫做erfc的函数,它是误差函数的补充版本。

2

return 后面不需要加 (),直接写 return P 也可以正常工作。

不过,这样做其实并不能解决你遇到的问题,因为 return(foo) 也应该可以正常使用。

如果能提供更多关于错误的信息,那会更有帮助。

7

你现在想要使用的模块是 scipy.integrate,但是你需要调用这个模块里面的某个函数。根据之前在聊天中的评论,你可能想用的是 scipy.integrate.quad()

另外,这个函数会返回一个包含 (结果, 最大误差) 的元组,所以你不能直接把 P_inner 用在 P 的计算中。正确的做法是 P = P_inner[0] + P_outer/2

撰写回答