【问题标题】:python quad: integrating over one variable while treating other variable as constant?python quad:对一个变量进行积分,同时将其他变量视为常量?
【发布时间】:2020-05-24 12:37:18
【问题描述】:

我正在做简单的集成,唯一的事情是我想保持'n'作为一个变量。我怎样才能在仍然集成超过 t 的同时做到这一点?

import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
import scipy.integrate as integrate
from scipy.integrate import quad
import math as m
y = lambda t: 3*t
T = 4      #period
n = 1
w = 2*np.pi*n/T

#for odd functions
def integrand(t):
    #return y*(2/T)*np.sin(w*t)
    return y(t)*np.sin(n*w*t)
Bn = (2/T)*quad(integrand,-T/2,T/2)[0]
print(Bn)

【问题讨论】:

    标签: python scipy numerical-integration


    【解决方案1】:

    使用四边形,你不能。也许您正在寻找 symbolic 集成,就像使用笔和纸一样; sympy 可以帮到你:

    import sympy
    
    x = sympy.Symbol("x")
    t = sympy.Symbol("t")
    T = sympy.Symbol("T")
    n = sympy.Symbol("n", positive=True)
    
    w = 2 * sympy.pi * n / T
    y = 3 * t
    
    out = 2 / T * sympy.integrate(y * sympy.sin(n * w * t), (t, -T/2, T/2))
    print(out)
    
    2*(-3*T**2*cos(pi*n**2)/(2*pi*n**2) + 3*T**2*sin(pi*n**2)/(2*pi**2*n**4))/T
    

    如果您想评估许多n 的积分,quadpy 可以提供帮助:

    import numpy as np
    from quadpy import quad
    
    y = lambda t: 3 * t
    T = 4
    n = np.linspace(0.5, 4.5, 20)
    w = 2 * np.pi * n / T
    
    
    # for odd functions
    def integrand(t):
        return y(t) * np.sin(np.multiply.outer(n * w, t))
    
    
    Bn = (2 / T) * quad(integrand, -T / 2, T / 2)[0]
    print(Bn)
    
    [ 2.95202424  4.88513496  4.77595051  1.32599514 -1.93954768 -0.23784853
      1.11558278 -0.95397681  0.63709387 -0.4752673   0.45818227 -0.4740128
      0.35943759 -0.01510463 -0.30348511  0.09861289  0.25428048  0.10030723
     -0.06099483 -0.13128359]
    

    【讨论】:

      猜你喜欢
      • 2016-04-06
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2020-08-31
      • 2017-07-27
      • 2013-01-29
      相关资源
      最近更新 更多