数值计算方法 求解初值问题(伪代码 c/c++ python)

求解初值问题,使用欧拉法,改进欧拉法,和四阶龙格库塔法求解。

伪代码

fun (input x, input y)
//举个例子,求解的初值问题的表达式为 y = 2xy
	return y <-2 *x*y

Elur (input step, input limit, input initial)
//欧拉法求解问题
	x <- 0
	y <- initial
	while x < limit:
		y <- y + step * fun(x,y)
		x <- x + step
	end
	return y
	
Elur_Advance (input step, input limit, input initial)
//改进欧拉法求解初值问题
	x <- 0
	y <- initial
	while x < limit:
		yp <- y + step * fun(x,y)
		yc <- y + step * fun(x,yp)
		x < x + step
	end
	return y

Runge_Kutta(input step, input limit, input initial)
//四阶龙格库塔法求解初值问题
	x <- 0
	y <- initial
	while x < limit:
		k1 <- fun(x,y);
		k2 <- fun(x+step/2,y+(k1*step/2))
		k3 <- fun(x+step/2,y+(k2*step/2))
		k4 <- fun(x+step,y+(k3*step))
		y <- y + (k1+2*k2+2*k3+k4)*step/6
		x <- x + step
	end
	retrun y

c/c++:

#include <iostream>
using namespace std;
double fun(double x,double y);
double Elur (double step, double limit, double initial);
double Elur_advance(double step, double limit, double initial);
double Runge_Kutta(double step, double limit, double initial);
int main()
{
	cout << Runge_Kutta(0.2,0.2,1);
}
double fun(double x,double y)
{
	return 2*x*y;
}
double Elur (double step, double limit, double initial)
{
	double x,y;
	x = 0;
	y = initial;
	while (x < limit)
	{
		y = y + step * fun(x,y);
		x = x + step;
	}
	return y;
}

double Elur_advance(double step, double limit, double initial)
{
	double x,yp,yc,y;
	x = 0;
	y = initial;
	while (x < limit)
	{
		yp = y + step * fun(x,y);
		yc = y + step * fun(x,yp);
		y = (yp + yc)/2;
		x = x + step;
	}
	return y;
}

double Runge_Kutta(double step, double limit, double initial)
{
	double x,k1,k2,k3,k4,y;
	x = 0;
	y = initial;
	while (x < limit)
	{
		k1 = fun(x,y);
		k2 = fun(x+step/2,y+(k1*step/2));
		k3 = fun(x+step/2,y+(k2*step/2));
		k4 = fun(x+step,y+(k3*step));
		y = y + (k1+2*k2+2*k3+k4)*step/6;
		x = x + step;
	}
	return y;
}


python:

def fun(x, y):
    return 2 * x * y

def Elur(step, limit, initial):
    x = 0
    y = initial
    while x < limit:
        y = y + step * fun(x,y)
        x = x + step
    return y

def Elur_Advanced(step, limit, initial):
    x = 0
    y = initial
    while x < limit:
        yp = y + step * fun(x, y)
        yc = y + step * fun(x, yp)
        y = (yp + yc) / 2
        x = x + step
    return y

def Runge_Kutta(step, limit, initial):
    x = 0
    y = initial
    while x < limit:
        k1 = fun(x, y)
        k2 = fun(x + step / 2, y + (k1 * step / 2))
        k3 = fun(x + step / 2, y + (k2 * step / 2))
        k4 = fun(x + step, y + (k3 * step))
        y = y + (k1 + 2 * k2 + 2 * k3 + k4) * step / 6
        x = x + step
    return y

print Runge_Kutta(0.2,0.2,1)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值