CSharp Runge-Kutta龙格-库塔法 源代码
时间: 2023-10-04 16:08:49 浏览: 272
以下是使用C#编写的Runge-Kutta龙格-库塔法的源代码示例:
```
using System;
public class RungeKutta
{
public static void Main()
{
// Define the ODE: y' = f(t, y) = 2t + y
Func<double, double, double> f = (t, y) => 2 * t + y;
// Define the initial condition: y(0) = 1
double y0 = 1;
// Define the time interval: 0 <= t <= 1
double t0 = 0;
double tf = 1;
// Define the step size
double h = 0.1;
// Calculate the number of steps
int n = (int)((tf - t0) / h);
// Initialize the solution array
double[] y = new double[n + 1];
y[0] = y0;
// Apply the Runge-Kutta method
for (int i = 0; i < n; i++)
{
double k1 = h * f(t0 + i * h, y[i]);
double k2 = h * f(t0 + i * h + h / 2, y[i] + k1 / 2);
double k3 = h * f(t0 + i * h + h / 2, y[i] + k2 / 2);
double k4 = h * f(t0 + i * h + h, y[i] + k3);
y[i + 1] = y[i] + 1.0 / 6.0 * (k1 + 2 * k2 + 2 * k3 + k4);
}
// Print the solution
for (int i = 0; i <= n; i++)
{
Console.WriteLine("y({0:F1}) = {1:F4}", t0 + i * h, y[i]);
}
}
}
```
该示例中,我们定义了一个函数f,代表常微分方程的形式y' = f(t, y)。然后,我们定义了初始条件y0,时间间隔t0到tf,并指定了步长h。我们使用RK4方法来求解ODE,并将结果存储在数组y中。最后,我们输出数组y的元素,以展示ODE的解。
阅读全文
相关推荐
















