2017-05-26 79 views
-1

我对C中的编码颇为陌生。 我试图以一种非常简单的方式将欧拉方法应用于一阶ODE,既作为迭代也作为递归函数。我不能把递归实现放在一起。欧拉方法递归

#include <stdio.h> 
#include <stdlib.h> 

float a,b,x,y,h,b; 

float fun(float x,float y) 
{ 
    float f; 
    f=x+y; 
    return f; 
} 

float euler (float x, float y, float h, float t){ 
    float k; 
    while(x<=b) { 
     y=y+h*fun(x,y);; 
     x=x+h; 
     printf("%0.3f\t%0.3f\n",x,y); 
     } 
    }; 

float euler_rec (float x, float y, float h, float b){ 
    if (x<=b) { 
     y=euler_rec(x, y, h, b)+h*fun(x,y); 
     } 
    else { 
     printf("%0.3f\t%0.3f\n",x,y); 
     } 
    }; 

int main() 
{ 

    printf("\nEnter x0,y0,h,xn: "); 
    scanf("%f%f%f%f",&x,&y,&h,&b); 

    printf("\n x\t y\n"); 

    euler(x, y, h, b); 

printf ("rec\n"); 
    euler_rec(x, y, h, b); 


return 0; 
} 

回答

0

我不推荐在严重的应用程序中使用数千或数千的递归深度。但是为了原理的缘故,你试图实现的是在时间x处返回解近似,初始点为(x0,y0)。因此,递归调用应该是

yprev = euler_rec(x0,y0,h,x-h); 
y = yprev + h*f(x-h,yprev); 

并且你必须构造递归函数的主体。


应该达到什么样

float euler_rec (float x0, float y0, float h, float x) { 
    float y; 
    if(x > x0+h) { 
     y = euler_rec(x0 ,y0 ,h , x-h); 
    } else { 
     y = y0; 
     h = x-x0; 
    } 
    return y + h * f(x-h, y); 
} 

印刷具有递归之外发生,或者你需要另一个参数是通过递归来表示对其中一些x值不变打印出来应该会发生。


您当然也可以使用几乎不是递归的前向递归,因为任何优化编译器都会将其转换为迭代。先前的变体是第一次递归调用,第二次是计算。如果你第一次把计算,递归调用第二则该方法读取,

float euler_rec (float x, float y, float h, float b){ 
    if (x+1.01*h>=b) { 
     h = b-x; 
     return y + h * f(x,y); // insert print statement if you like 
    } 
    return euler_rec(x+h, y+h*f(x,y),h,b) 
} 
+0

条件'X == x0'具有非常低的概率,由于浮点错误而实际上打,即使理论上所有的拟合。如果你不假设'h'均匀分配到'x-x0',那么你会更加健壮。 – LutzL

+0

这里我得到了起始值x0,y0。 'float euler_rec(float x0,float y0,float h,float x){' 'float yprev,y;' 'y = y0;' 'if if(x> x0){' 'yprev = euler_rec(x0 ,y0,h,xh);' 'y = yprev + h * f(xh,yprev);' 'x = xh; '}'' 其他{'' 的printf( “%0.3f \ T%0.3f \ n”,X,Y);'' }'' }' –

+0

你注意到你正在做什么用计算值“y”?什么是回报价值? – LutzL