计算方法实验(三):四阶龙格-库塔方法

四阶Runge-Kutta数学原理

给定常微分方程初值问题

{ dy dx = f ( x , y ) , a ≤ x ≤ b   y ( a ) = α         h = b − a N   \left\{ \begin{matrix} \frac{\text{dy}}{\text{dx}} = f(x,y),a \leq x \leq b \\ \ y(a) = \alpha\text{\;\;\quad\;h} = \frac{b - a}{N} \\ \end{matrix} \right.\ {dxdy=f(x,y),axb y(a)=αh=Nba 

x n = a + n ⋅ h x_{n} = a + n \cdot h xn=a+nh n = 0 , 1 , ⋯   , N n = 0,1,\cdots,N n=0,1,,N,利用四阶龙格—库塔方法

K 1 = h f ( x n , y n ) K_{1} = hf\left( x_{n},y_{n} \right) K1=hf(xn,yn)

K 2 = h f ( x n + h 2 , y n + K 1 2 ) K_{2} = hf\left( x_{n} + \frac{h}{2},y_{n} + \frac{K_{1}}{2} \right) K2=hf(xn+2h,yn+2K1)

K 3 = h f ( x n + h 2 , y n + K 2 2 ) K_{3} = hf\left( x_{n} + \frac{h}{2},y_{n} + \frac{K_{2}}{2} \right) K3=hf(xn+2h,yn+2K2)

K 4 = h f ( x n + h , y n + K 3 ) K_{4} = hf\left( x_{n} + h,y_{n} + K_{3} \right) K4=hf(xn+h,yn+K3)

y n + 1 = y n + 1 6 ( K 1 + 2 K 2 + 2 K 3 + K 4 ) y_{n + 1} = y_{n} + \frac{1}{6}(K_{1} + 2K_{2} + 2K_{3} + K_{4}) yn+1=yn+61(K1+2K2+2K3+K4)

n = 0 , 1 , ⋯   , N − 1 n = 0,1,\cdots,N - 1 n=0,1,,N1

可逐次求出微分方程初值问题的数值解 y n y_{n} yn n = 1 , 2 , ⋯   , N n = 1,2,\cdots,N n=1,2,,N

程序流程

核心代码

#include <cmath>
#include <cstdio>
#include <iostream>
using namespace std;

int n;
double a, b, fa;

double f(double x, double y) { return -y * y; }
double f_(double x) { return 1.0 / (x + 1.0); }

int main() {
    scanf("%lf%lf%lf%d", &a, &b, &fa, &n);
    double x = a, y = fa, h = (b - a) / n;
    for (int i = 1; i <= n; i++) {
        double k1 = h * f(x, y);
        double k2 = h * f(x + h / 2, y + k1 / 2);
        double k3 = h * f(x + h / 2, y + k2 / 2);
        double k4 = h * f(x + h, y + k3);
        x += h;
        y += 1.0 / 6.0 * (k1 + 2 * k2 + 2 * k3 + k4);
        printf("%.2lf\t%lf\t%.2lf\n", x, y, fabs(f_(x) - y));
    }
    return 0;
}

详细报告

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值