Python:使用 scipy quad 嵌套在另一个积分中的积分和函数 [英] Python: Integral and funcion nested in another integral using scipy quad

查看:108
本文介绍了Python:使用 scipy quad 嵌套在另一个积分中的积分和函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经设法使用 scipy.integrate.quad 为我的随机过程类编写了几行代码

I have managed to write a few lines of code using scipy.integrate.quad for my stochastic process class

我有标准布朗运动的马尔可夫转移函数

I have the Markov transition function for standard Brownian motion

import numpy as np
def p(x,t):
    return (1/np.sqrt(2*np.pi*t))*np.exp(-x**2/(2*t))

但我想计算以下我将用不起作用的代码编写的内容.我是这样写的,所以我们不用乳胶也能理解问题.

But I want to compute the following that I am going to write in code that would not work. I write it like this so we can understand the problem without the use of latex.

 from scipy.integrate import quad
 integral = quad(quad(p(y-x),1,np.inf)*p(x,1),1,np.inf) 

您可能注意到问题在于内部积分中发生的二元事件.我做了以下但不确定:

You probably noticed that the problem is the bivariate thing going on in the inner integral. I did the following but am unsure of it:

p_xy = lambda y,x: p(y-x,1)
inner = lambda x : quad(p_xy,1,np.inf,args = (x,))[0]
outer = lambda x: inner(x)*p(x,1)
integral = quad(outer,1,np.inf)[0]

然后我得到

 0.10806767286289147

我喜欢 Python 及其 lambda 函数,但似乎不确定这一点.你的想法是什么?感谢您抽出宝贵时间.

I love Python and its lambda functions but seem to not be sure about this. What are your thoughts? Thank you for your time.

推荐答案

对于您希望执行的积分类型,二元积分,SciPy 有 专用例程.

For the type of integral you wish to perform, bivariate integrals, SciPy has dedicated routines.

优点是这些例程更容易处理复杂的边界(例如,边界是否依赖于另一个坐标).

The advantage is that these routines handle complex boundaries more easily (were the bounds depend on the other coordinate, for instance).

我将您的示例重写为:

import numpy as np
from scipy.integrate import nquad

def p(x,t):
    return (1/np.sqrt(2*np.pi*t))*np.exp(-x**2/(2*t))

def integrand(x, y):
    return p(y-x, 1)*p(x, 1)

integral = nquad(integrand, ((1, np.inf), (1, np.inf)))

print(integral[0])

打印出相同的结果.我相信上面的代码更容易阅读,因为被积函数被明确地写成两个变量的函数.

which prints out the same result. I believe that the code above is easier to read as the integrand is written explicitly as a function of the two variables.

这篇关于Python:使用 scipy quad 嵌套在另一个积分中的积分和函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆