简体   繁体   English

Python:集成指数和高斯函数的乘积

[英]Python: Integrate product of exponential and gaussian function

I have a function y which is a product of y1 = exp(-x) and exp(-x^2): 我有一个函数y,它是y1 = exp(-x)和exp(-x ^ 2)的乘积:

y1 = exp(-x) y1 = exp(-x)

y2 = exp(-x**2) y2 = exp(-x ** 2)

y = y1*y2 = exp(-x)*exp(-x**2) = exp(-x **2-x) y = y1 * y2 = exp(-x)* exp(-x ** 2)= exp(-x ** 2-x)

Integrating the functions y1 or y2 works fine using sympy: 使用sympy集成函数y1或y2可以正常工作:

>>> import sympy as sy
>>> import numpy as np
>>> x = sy.Symbol('x')
>>> y1 = sy.exp(-x)
>>> sy.integrate(y1, (x, 0, np.inf))
1

and

>>> y2 = sy.exp(-x**2)
>>> sy.integrate(y2, (x, 0, np.inf))
0.5*sqrt(pi)

However, whenever I'm trying to integrate the product y1*y2 = y, the integral is not accepted: 但是,每当我尝试对乘积y1 * y2 = y进行积分时,均不接受积分:

>>> y = y1*y2
>>> sy.integrate(y, (x, 0, np.inf))
Integral(exp(-x)*exp(-x**2), (x, 0, np.inf))

Perhaps I'm blind and missing something obvious. 也许我是盲人,缺少明显的东西。

If sympy cannot evaluate it symbolically, then it just returns an Integral object. 如果sympy无法对其进行符号评估,则它仅返回一个Integral对象。 You need to either use a more powerful symbolic calculator like maxima or Wolfram|Alpha (link to solution) ), or else resort to numerical integration. 您需要使用功能更强大的符号计算器,例如maximaWolfram | Alpha(指向解决方案的链接) ),或者诉诸于数值积分。 Here are a few options for numerically integrating it: 这是一些将其数字积分的选项:

import sympy as sy
import numpy as np
import scipy as sp
import scipy.integrate

x = sy.Symbol('x')
y1 = sy.exp(-x)
y2 = sy.exp(-x**2)
y = y1*y2

# Pure scipy without sympy
print(sp.integrate.quad(lambda x: np.exp(-x) * np.exp(-(x**2)), 0, np.inf))

# Mix of scipy and sympy
print(sp.integrate.quad(lambda x_arg: y.subs(x, x_arg).evalf(), 0, np.inf))

# Without using scipy
print(sy.mpmath.quad(sy.lambdify([x], y), [0, np.inf]))

I believe the Integral is being accepted and it is giving you a valid sympy result. 我相信积分被接受,并且为您提供了有效的象征性结果。 I used this site and it indicates (I am not enough of a mathematician to verify it) the answer has the error function (erf) in it: 我使用了这个站点 ,它表明(我还不够数学家来验证),答案中包含错误函数(erf):

在此处输入图片说明

There is no exact analytical answer, so it is giving you it's internal representation. 没有确切的分析答案,因此它可以为您提供内部表示。 I used Mathematica years ago and it would do something similar, but it provided a polynomial approximation to the solution. 几年前,我使用Mathematica,它会做类似的事情,但是它提供了该解决方案的多项式近似。 BTW, the answer is approximately 0.5456413607650471. 顺便说一句,答案约为0.5456413607650471。

I used http://www.codecogs.com/latex/eqneditor.php to generate the equation image. 我使用http://www.codecogs.com/latex/eqneditor.php生成方程式图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM