python - 快速帮助在 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
解决方案
您可以将明确的上限替换为 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)
推荐阅读
- django - 当我执行 PUT/PATCH 时,如何在不删除实际对象数据的情况下从多对多关系的实例表中删除对象
- php - PHP -> 如何在注册查询中绑定多个值?
- python - 如何在 django 模型中使用枚举作为选择字段
- excel - 使用 VBA 将行添加到表的现有范围
- go - 如何从登录将会话数据存储在 chi 路由器上下文中
- angular - 取消订阅连接的可观察对象的销毁
- rest - 使用类似过滤器的条件设计 rest API
- c# - 拆分列表
基于项目长度 - graphql - req 在 Apollo Server 上下文中始终未定义
- laravel - 正确的 if-else 分组 Laravel