Home > Back-end >  Run time errors while computing e^x
Run time errors while computing e^x

Time:02-23

Continuing from the question I posted before How to increase precision for function e^x

I made few changes in my code by taking advices given

#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;
}

But I am not getting any output its just giving run time error(http://codepad.org/jIKoYGFC) and I don't know why . Please can some one help me why I am getting these errors

CodePudding user response:

That loop is completely bogus. You're not writing an iterative function (where it would make more sense). Further you have an edge case of zero returning undefined content.

Though I do not recommend floating point for loop control, nor do I advise thousands of invocations into recursive calls, your code should be more like

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;
}

which ultimately is just this:

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);
}

Fixing that (either way):

#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;
}

Output

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