如何使用 while 循环执行数值积分?

问题描述 投票:0回答:0

我知道您可以通过创建一个 while 循环并改变您的“dt”值来求导数,但是是否有类似的方法来进行积分?以下是我正在考虑的衍生品示例:)

编辑:我想我应该更具体(抱歉,我还没有完善提问的艺术),但更具体地说,在下面的示例代码中,我有一个钟摆角加速度的微分方程。假设我有角位置的方程式,我如何积分才能获得显示角速度/角加速度图表的数据列表?

import numpy as np
import matplotlib.pyplot as plt

g=9.8 #m/s**2
L=.3 #m
omega=0 #initial angular velocity
theta=np.deg2rad(1) #initial angular position
t=0
tmax=3
dt=1e-4

#Creating lists to store data
Time=[]
Theta=[]
Omega=[]
A=[]

def d2theta(x): #function for angular acceleration, dependent upon angular position
    a=-(g/L)*np.sin(x)
    return a

#def T(x): #Calculates the period of a pendulum with an initial angular position theta and an initial angular velocity of 0
    

a=d2theta(theta) #initial angular acceleration

Ts=2*np.pi*np.sqrt(L/g) #Gives the period length for small angles
print("For small angles, the period length is about",Ts,"seconds.")

while t<tmax:
    a=d2theta(theta)
    omega+=a*dt
    theta+=omega*dt
    Time.append(t)
    Theta.append(theta)
    Omega.append(omega)
    A.append(a)
    t+=dt
    if omega==0:
        t=0
        theta+=np.deg2rad(1)

plt.plot(Time,Theta)
plt.show()
plt.plot(Time,Omega)
plt.show()
plt.plot(Time,A)
python derivative integral
© www.soinside.com 2019 - 2024. All rights reserved.