用C++实现四阶Runge-Kutta法求解微分方程组

比较简单,照着公式算就可以了。

#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
#define eps 1e-6
typedef long long ll;

const ll N = 1e3;

double x[N];
double y[N];

double f(double x, double y)
{
    return ( 0.0 - y + x*x + 4*x -1) / 2;
}


int main()
{
    double a, b, y0;
    int n;
    cin>>n;
    cin>>a>>b>>y0;
    double h = (b-a) / n;
    x[0] = a;
    y[0] = y0;
    for(int i=1; i<=n; i++)
    {
        x[i] = x[i-1] + h;
        double k1 = f(x[i-1], y[i-1]);
        double k2 = f(x[i-1]+h/2, y[i-1]+h*k1/2.0);
        double k3 = f(x[i-1]+h/2, y[i-1]+h*k2/2.0);
        double k4 = f(x[i-1]+h, y[i-1]+h*k3);
        y[i] = y[i-1] + h * ( k1 + 2*k2 + 2*k3 + k4 )/6.0;
    }

    for(int i=0; i<=n; i++)
    {
        printf("%.6f\t", x[i]);
    }
    cout<<endl;
    for(int i=0; i<=n; i++)
    {
        printf("%.6f\t", y[i]);
    }
    cout<<endl;

    system("pause");
    return 0;

}

输入三个数,n所要求的点的数量,a , b为所求区间,y0为初值y(a)。

test :

5
0 1
0
0.000000        0.200000        0.400000        0.600000        0.800000        1.000000
0.000000        -0.055162       -0.021268       0.100821        0.310323        0.606534

  • 4
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值