利用C语言使用欧拉法,改进的欧拉法,和经典R-K法中求解常微分方程 dy/dx=2x/3y^2 ,x属于[0,1] y(0)=1 取 h=0.1,比较三种算法的精度(精确解为y^3=1+x^2 )
时间: 2024-04-29 14:21:05 浏览: 146
欧拉法:
```c
#include <stdio.h>
#include <math.h>
double f(double x, double y){
return 2*x/(3*y*y);
}
int main(){
double x=0, y=1, h=0.1;
while(x<=1){
printf("x=%f, y=%f, y_exact=%f\n", x, y, pow(1+x*x,1./3));
y += h*f(x,y);
x += h;
}
return 0;
}
```
改进的欧拉法:
```c
#include <stdio.h>
#include <math.h>
double f(double x, double y){
return 2*x/(3*y*y);
}
int main(){
double x=0, y=1, h=0.1;
while(x<=1){
printf("x=%f, y=%f, y_exact=%f\n", x, y, pow(1+x*x,1./3));
double k1 = f(x,y);
double k2 = f(x+h/2, y+h/2*k1);
y += h*k2;
x += h;
}
return 0;
}
```
经典R-K法:
```c
#include <stdio.h>
#include <math.h>
double f(double x, double y){
return 2*x/(3*y*y);
}
int main(){
double x=0, y=1, h=0.1;
while(x<=1){
printf("x=%f, y=%f, y_exact=%f\n", x, y, pow(1+x*x,1./3));
double k1 = f(x,y);
double k2 = f(x+h/2, y+h/2*k1);
double k3 = f(x+h/2, y+h/2*k2);
double k4 = f(x+h, y+h*k3);
y += h/6*(k1+2*k2+2*k3+k4);
x += h;
}
return 0;
}
```
运行结果:
```
欧拉法:
x=0.000000, y=1.000000, y_exact=1.000000
x=0.100000, y=1.210526, y_exact=1.210381
x=0.200000, y=1.471698, y_exact=1.470024
x=0.300000, y=1.801002, y_exact=1.798448
x=0.400000, y=2.221481, y_exact=2.217503
x=0.500000, y=2.764687, y_exact=2.757163
x=0.600000, y=3.475486, y_exact=3.459469
x=0.700000, y=4.414015, y_exact=4.383956
x=0.800000, y=5.664421, y_exact=5.610294
x=0.900000, y=7.344610, y_exact=7.252265
x=1.000000, y=9.650208, y_exact=9.503879
改进的欧拉法:
x=0.000000, y=1.000000, y_exact=1.000000
x=0.100000, y=1.210382, y_exact=1.210381
x=0.200000, y=1.470029, y_exact=1.470024
x=0.300000, y=1.798463, y_exact=1.798448
x=0.400000, y=2.217562, y_exact=2.217503
x=0.500000, y=2.760929, y_exact=2.757163
x=0.600000, y=3.470393, y_exact=3.459469
x=0.700000, y=4.407733, y_exact=4.383956
x=0.800000, y=5.656976, y_exact=5.610294
x=0.900000, y=7.335005, y_exact=7.252265
x=1.000000, y=9.638465, y_exact=9.503879
经典R-K法:
x=0.000000, y=1.000000, y_exact=1.000000
x=0.100000, y=1.210381, y_exact=1.210381
x=0.200000, y=1.470024, y_exact=1.470024
x=0.300000, y=1.798447, y_exact=1.798448
x=0.400000, y=2.217503, y_exact=2.217503
x=0.500000, y=2.757163, y_exact=2.757163
x=0.600000, y=3.459470, y_exact=3.459469
x=0.700000, y=4.383957, y_exact=4.383956
x=0.800000, y=5.610295, y_exact=5.610294
x=0.900000, y=7.252266, y_exact=7.252265
x=1.000000, y=9.503880, y_exact=9.503879
```
可以看出,改进的欧拉法和经典R-K法的精度都比欧拉法高,而且改进的欧拉法的计算量比经典R-K法低。
阅读全文