首页 > 解决方案 > 快速帮助在 for 循环中设置方程的总和?

问题描述

我只是想将倒数第三行(在注释 n=3 中表示)转换为求和 for 循环,在该循环中我可以简单地输入 n 的值,而不是像下面那样手动求和:

import sympy as sp

#input*************************************
T = 2
n = sp.Symbol('n',integer=True,positive=True)
t = sp.symbols('t')
F = 1
#***************************************

wT = 2*sp.pi/T #frequency

A0=sp.integrate(F,t) #integrate wrt t
A0=A0.subs(t,1)-A0.subs(t,0) #integrating from t=0 to t=T. MUST USE BOTH SUBS TO GET PROPER ANSWER
A0 = (2/T)*A0 #make sure to mutiply constants AFTER subs
print('A0:', A0)

F_An=F*sp.cos(n*wT*t)
An = sp.integrate(F_An,t)
An=An.subs(t,1)-An.subs(t,0)
An = (2/T)*An
print('An:', An)

F_Bn=F*sp.sin(n*wT*t)
Bn = sp.integrate(F_Bn,t)
Bn=Bn.subs(t,1)-Bn.subs(t,0)
Bn = (2/T)*Bn
print('Bn:', Bn)

#to get numerical answer @ n=1, do for A0, An, Bn
#Bn=Bn.subs(n,1)
#F without A0 for summing purposes:


F= An*sp.cos(n*wT*t)+Bn*sp.sin(n*wT*t)

F=F.subs(n,1)+F.subs(n,2)+F.subs(n,3) #for n=3
F=F+A0/2
F

标签: pythonsympy

解决方案


您可以将明确的上限替换为 Sum ,当您doit获得所需的表达式时:

>>> from sympy import Sum
>>> from sympy.abc import i, n
>>> Sum(cos(i),(i,1,n)).subs(n,3).doit()
cos(3) + cos(2) + cos(1)

推荐阅读