numpy Sympy似乎不对变量的指数进行积分(MATLAB可以)

zd287kbt  于 2023-05-17  发布在  Matlab
关注(0)|答案(1)|浏览(134)

我想对函数S(w)进行积分

import sympy as sym

w = sym.Symbol('w')
Spm = 0.95**4/w**5*sym.exp(-5/4*(0.95/w)**4)
S = sym.Piecewise(
      (Spm**sym.exp(-1/2*((w-0.95)/(0.07*0.95))**2), w<=0.95),
      (Spm**sym.exp(-1/2*((w-0.95)/(0.09*0.95))**2), w>0.95))

S_int = sym.integrate(S, (w, 0.8, 1.0))

看来**sym.exp()是个问题
如果我把函数简化为下面的函数,那么积分就计算成功了。

S = sym.Piecewise(
     (Spm**((0.07*0.95))**2), w<=0.95),
     (Spm**((0.09*0.95))**2), w>0.95))

MATLAB使用'ArrayValue'轻松计算积分。

Spm = @(w) 0.95^4./w.^5.*exp(-5/4*(0.95./w).^4);

S = @(w) ...
    Spm(w).^exp(-1/2*((w-0.95)/(0.07*0.95)).^2).*(w <= 0.95) + ...
    Spm(w).^exp(-1/2*((w-0.95)/(0.09*0.95)).^2).*(w > 0.95);

S_int = integral(S, 0.8, 1.0, 'ArrayValued', true);

Sympy或Numpy中是否有等效功能?

6g8kf2rb

6g8kf2rb1#

以下是数值计算积分的可能解决方案:

import sympy as sym
import numpy as np
from sympy.utilities.lambdify import lambdify

w = sym.Symbol('w')
Spm = 0.95**4/w**5*sym.exp(-5/4*(0.95/w)**4)
S = sym.Piecewise(
     (Spm**sym.exp(-1/2*((w-0.95)/(0.07*0.95))**2), w<=0.95),
     (Spm**sym.exp(-1/2*((w-0.95)/(0.09*0.95))**2), w>0.95))

dw = 0.001
len_dw = int(np.ceil((1.0-0.8)/dw) + 1)
w_arr = np.linspace(0.8, 1.0, len_dw)
S_func = lambdify(w, S, 'numpy')   # Returns a numpy-ready function
S_array = S_func(w_arr)            # S_func evaluated at w_func

S_int = np.trapz(S_array, w_arr)

相关问题