[英]Solving differential equations numerically
I tried solving a very simple equation f = t**2 numerically.我尝试用数值求解一个非常简单的方程 f = t**2。 I coded a for-loop, so as to use f for the first time step and then use the solution of every loop through as the inital function for the next loop.
我编写了一个 for 循环,以便在第一次使用 f 步骤,然后使用每个循环的解决方案作为下一个循环的初始 function。
I am not sure if my approach to solve it numerically is correct and for some reason my loop only works twice (one through the if- then the else-statement) and then just gives zeros.我不确定我在数字上解决它的方法是否正确,并且由于某种原因,我的循环只工作了两次(一次通过 if- 然后是 else 语句),然后只给出零。
Any help very much appreciatet.非常感谢任何帮助。 Thanks!!!
谢谢!!!
## IMPORT PACKAGES
import numpy as np
import math
import sympy as sym
import matplotlib.pyplot as plt
## Loop to solve numerically
for i in range(1,4,1):
if i == 1:
f_old = t**2
print(f_old)
else:
f_old = sym.diff(f_old, t).evalf(subs={t: i})
f_new = f_old + dt * (-0.5 * f_old)
f_old = f_new
print(f_old)
Scipy.integrate package has a function called odeint that is used for solving differential equations Scipy.integrate package 有一个名为 odeint 的 function 用于求解微分方程
Here are some resources Link 1 Link 2这里有一些资源Link 1 Link 2
y = odeint(model, y0, t)
model: Function name that returns derivative values at requested y and t values as dydt = model(y,t) model:Function 名称,返回请求的 y 和 t 值的导数值为 dydt = model(y,t)
y0: Initial conditions of the differential states y0:微分状态的初始条件
t: Time points at which the solution should be reported. t:应该报告解决方案的时间点。 Additional internal points are often calculated to maintain accuracy of the solution but are not reported.
通常会计算额外的内部点以保持解决方案的准确性,但不会报告。
Example that plots the results as well:也绘制结果的示例:
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# function that returns dy/dt
def model(y,t):
k = 0.3
dydt = -k * y
return dydt
# initial condition
y0 = 5
# time points
t = np.linspace(0,20)
# solve ODE
y = odeint(model,y0,t)
# plot results
plt.plot(t,y)
plt.xlabel('time')
plt.ylabel('y(t)')
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.