如何计算exp(a * x ** 2 + b * x + c)的积分?

时间:2020-10-19 11:38:04

标签: python sympy

所以我想使用sympy假设exp(-ax^2-bx-c)来计算a>0, b>0, c>0的积分。

所以我做到了:

from sympy import *

x = symbols('x')
a, b, c = symbols('a, b, c')
assumptions = Q.real(a), Q.positive(a), \
              Q.real(b), Q.positive(b), \
              Q.real(c), Q.positive(c)

with assuming(*assumptions):
    expression = exp(-a*x**2 - b*x - c)
    ans = integrate(expression, (x, -oo, oo))
    ans = simplify(ans)

print(str(ans).replace(',', ',\n\n'))

我明白了:

Piecewise((sqrt(pi)*(erf(b/(2*sqrt(a))) + erfc(b/(2*sqrt(a))) + 1)*exp(-c + b**2/(4*a))/(2*sqrt(a)),

 (Abs(arg(a)) < pi/2) | ((Abs(arg(a)) <= pi/2) & (2*Abs(arg(b)) < pi) & (Abs(2*arg(b) + 2*pi) < pi))),

 (Integral(exp(-a*x**2 - b*x - c),

 (x,

 -oo,

 oo)),

 True))

但是我知道,答案必须是:

sqrt(pi/a) * exp(b**2/(4*a) - c)

按照我的想法,假设没有用,所以我尝试了这个:

from sympy import *

a = symbols('a')
assumptions = [ Q.positive(a) ]
with assuming(*assumptions):
    print(ask(Q.is_true(a > 0)))

答案是:

None

这很奇怪。我在做什么错了?

1 个答案:

答案 0 :(得分:1)

sympy文档对此感到困惑。您正在尝试使用“新”假设系统,该系统仍处于试验阶段,实际上并未由sympy内部使用。您需要使用在创建符号时设置假设的核心假设系统:

In [50]: from sympy import * 
    ...:  
    ...: x = symbols('x') 
    ...: a, b, c = symbols('a, b, c', positive=True)                                                                                           

In [51]: integrate(exp(-a*x**2 - b*x - c), (x, -oo, oo))                                                                                       
Out[51]: 
  ⎛         2                     ⎞                             
  ⎜        b                     2⎟                             
  ⎜       ───                   b ⎟                 2           
  ⎜       4⋅a    ⎛ b  ⎞        ───⎟                b            
  ⎜  π⋅b⋅ℯ   ⋅erf⎜────⎟        4⋅a⎟               ───           
  ⎜              ⎝2⋅√a⎠   π⋅b⋅ℯ   ⎟  -c       -c  4⋅a     ⎛ b  ⎞
  ⎜- ────────────────── - ────────⎟⋅ℯ     √π⋅ℯ  ⋅ℯ   ⋅erfc⎜────⎟
  ⎝         2⋅√a            2⋅√a  ⎠                       ⎝2⋅√a⎠
- ───────────────────────────────────── + ──────────────────────
                   √π⋅b                            2⋅√a         

该结果可以简化。看来simple不能处理erf plus erfc,但我们可以提供一些帮助:

In [52]: integrate(exp(-a*x**2 - b*x - c), (x, -oo, oo)).simplify()                                                                            
Out[52]: 
                                        2
                                       b 
                                 -c + ───
   ⎛   ⎛ b  ⎞       ⎛ b  ⎞    ⎞       4⋅a
√π⋅⎜erf⎜────⎟ + erfc⎜────⎟ + 1⎟⋅ℯ        
   ⎝   ⎝2⋅√a⎠       ⎝2⋅√a⎠    ⎠          
─────────────────────────────────────────
                   2⋅√a                  

In [53]: integrate(exp(-a*x**2 - b*x - c), (x, -oo, oo)).simplify().rewrite(erfc)                                                              
Out[53]: 
           2
          b 
    -c + ───
         4⋅a
√π⋅ℯ        
────────────
     √a 
相关问题