【问题标题】:Solving differential equations numerically数值求解微分方程
【发布时间】:2020-06-05 10:34:21
【问题描述】:

我尝试用数值求解一个非常简单的方程 f = t**2。我编写了一个for循环,以便在第一个时间步使用f,然后将每个循环的解作为下一个循环的初始函数。

我不确定我的数值求解方法是否正确,并且由于某种原因,我的循环只工作了两次(一次通过 if- 然后是 else 语句),然后只给出零。

非常感谢任何帮助。谢谢!!!

## 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)

【问题讨论】:

  • 不清楚您要达到的目标。请发布您的输出和预期输出。

标签: python for-loop if-statement differential-equations derivative


【解决方案1】:

Scipy.integrate 包有一个名为 odeint 的函数,用于求解微分方程

这里有一些资源 Link 1 Link 2

y = odeint(model, y0, t)

model:函数名称,返回请求的 y 和 t 值的导数值为 dydt = model(y,t)

y0:微分状态的初始条件

t:应该报告解决方案的时间点。通常会计算额外的内部点以保持解决方案的准确性,但不会报告。

也绘制结果的示例:

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()



【讨论】:

    猜你喜欢
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 1970-01-01
    • 2014-07-25
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多