求解初值问题,使用欧拉法,改进欧拉法,和四阶龙格库塔法求解。
伪代码
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
#include
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;
}
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)