向前欧拉的python代码实现
时间: 2024-06-27 20:01:12 浏览: 102
向前欧拉方法是一种数值解微分方程的简单算法,用于估计连续时间系统的离散状态。以下是一个基本的Python实现,假设我们有一个一阶常微分方程dy/dt = f(t, y),初始条件为y0:
```python
import numpy as np
def forward_euler(f, tspan, y0, step_size):
"""
Forward Euler method implementation
Parameters:
f (function): The derivative function dy/dt = f(t, y)
tspan (tuple): Start and end time of the integration (t0, tf)
y0 (float or array): Initial value of y
step_size (float): Size of each time step
Returns:
times (numpy array): Array of time points
ys (numpy array): Array of estimated values for y at each time step
"""
t0, tf = tspan
n_steps = int((tf - t0) / step_size) + 1
times = np.linspace(t0, tf, n_steps)
ys = np.zeros_like(times)
# Set the first value
ys = y0
# Apply the forward Euler method
for i in range(1, len(times)):
ys[i] = ys[i-1] + f(times[i-1], ys[i-1]) * step_size
return times, ys
# Example usage
def example_derivative(t, y):
# Replace this with your actual derivative function
return 1.0
tspan = (0, 10)
y0 = 0
step_size = 0.1
times, ys = forward_euler(example_derivative, tspan, y0, step_size)
```
在这个例子中,`f(t, y)`是你需要提供的函数,表示dy/dt。`forward_euler`函数会根据给定的时间范围、初始值和步长计算出y值序列。
阅读全文