运行 计算 e^x 时出现时间错误

Run time errors while computing e^x

继续我之前发布的问题

我根据给出的建议对我的代码做了一些改动

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

long double exponential(long double x, long double n, long double p)
{
    long double i = 1;

    while (n > 0) // loop stops when becomes less than 0
        i = i + (x / p) * (exponential(x, n - 0.0001, p + 1));

    if (n < 0) // when n reaches 0 or becomes less than zero value of i will be returned
        return i;
}

int main()
{
    long double p, x, n;
    scanf("%Lf", &x);
    printf("math.h e^x =     %lf\n", exp(x));
    printf("calculated e^x = %Lf\n", exponential(x, 1, 1));
    return 0;
}

但我没有得到任何输出,它只是给出 运行 时间错误 (http://codepad.org/jIKoYGFC),我不知道为什么。请有人帮助我为什么会收到这些错误

那个循环完全是假的。您不是在编写迭代函数(它会更有意义)。此外,您有零返回未定义内容的边缘情况。

虽然我不建议将浮点数用于循环控制,也不建议将数千次调用转换为递归调用,但您的代码应该更像

long double exponential(long double x, long double n, long double p)
{
    long double i = 1;
    if (n > 0)
        i += (x / p) * (exponential(x, n - 0.0001, p + 1));
    return i;
}

最终就是这样:

long double exponential(long double x, long double n, long double p)
{
    return 1 + ((n > 0) ? (x / p) * exponential(x, n - 0.0001, p + 1) : 0);
}

解决这个问题(无论哪种方式):

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

long double exponential(long double x, long double n, long double p)
{
    return 1 + ((n > 0) ? (x / p) * exponential(x, n - 0.0001, p + 1) : 0);
}

int main()
{
    long double x = 5;
    printf("math.h e^x =     %Lf\n", expl(x));
    printf("calculated e^x = %Lf\n", exponential(x, 1, 1));
    return 0;
}

输出

math.h e^x =     148.413159
calculated e^x = 148.413159

出于好奇,使用 LibGMP 创建了一个版本,想看看这将如何改善结果。

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

#define BITS 128

上面一行平均尾数是128位,指数是64位。这是我基于 GMP 的功能:

void gmp_exponential(mpf_t * i, double x, double n, int p)
{
    mpf_t ii;
    mpf_init(ii);    
    mpf_set_d(ii,1);
    
    if (n > 0){
      mpf_t a,b,c;

      gmp_exponential(&ii, x, n - 0.0001, p + 1);
      
      mpf_inits (a, b, c, NULL);  
      mpf_set_d(a,x);
      mpf_div_ui(b, a, p) ;
      mpf_mul(c, b, ii);
      mpf_add (*i,*i,c);
      
      mpf_clears(a,b,c,NULL);
    }
    mpf_clear(ii);
}

重用 WhozCraig 中的函数进行比较:

long double exponential(long double x, long double n, long double p)
{
    return 1 + ((n > 0) ? (x / p) * exponential(x, n - 0.0001, p + 1) : 0);
}

并编码为 运行 全部:

int main()
{
  double x = 30.0;
  
  mpf_t i;
  mpf_init2 (i, BITS);    
  mpf_set_d(i,1);
  gmp_exponential(&i, x, 1, 1);
  
  printf     ("math.h e^x              =  %Lf\n", expl(x));
  gmp_printf ("calculated e^x with mpf =  %.*Ff\n", 6, i);
  printf     ("calculated e^x          =  %Lf\n", exponential(x, 1, 1));
  
  mpf_clear(i);
  return 0;
}

输出:

math.h e^x              =  10686474581524.462147
calculated e^x with mpf =  10686474581524.462143
calculated e^x          =  10686474581524.462149