exp function in C

The exp function in C computes the base-e exponential of x. A range error occurs if the magnitude of
finite x is too large. The x is the argument that is passed into the exp(). It is declared in math.h and takes one argument in the form of double and returns the value of type double.

 

Syntax of exp function in C:

//Syntax of exp

double exp(double x);

Parameters:

x => floating types (double)

Return value:

The exp functions return ex.

 

 

You can use the expf() function to work specifically with float and expl() to work with long double type. See the below syntax.

//other exp function in c

float expf(float x);

long double expl(long double x);

 

C program to understand the working of exp function:

Below mentioned C example code shows the usage of exp().

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

int main()
{
    double x = 12.0, result;

    result = exp(x);

    printf("exp of %.2lf = %.2lf", x, result);

    return 0;
}

Output:

exp of 2.00 = 7.39

 

Error handling

Errors are reported as specified in math_errhandling.

If the implementation supports IEEE floating-point arithmetic (IEC 60559),

  • If the argument is ±0, 1 is returned.
  • If the argument is -∞, +0 is returned.
  • If the argument is +∞, +∞ is returned.
  • If the argument is NaN, NaN is returned.
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <errno.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON

int main()
{
    // special values
    printf("exp(-0) = %f\n", exp(-0.0));
    printf("exp(-Inf) = %f\n", exp(-INFINITY));

    //error handling
    errno = 0;
    feclearexcept(FE_ALL_EXCEPT);
    printf("exp(710) = %f\n", exp(710));
    if(errno == ERANGE)
    {
        perror("errno == ERANGE");
    }
    if(fetestexcept(FE_OVERFLOW))
    {
        puts("FE_OVERFLOW raised");
    }

    return 0;
}

Output:

exp(-0) = 1.000000
exp(-Inf) = 0.000000
exp(710) = inf
errno == ERANGE: Numerical result out of range
FE_OVERFLOW raised

 

Note: The overflow is guaranteed if  x > 709.8, and underflow is guaranteed if x < -708.4, for IEEE-compatible type double.

 

Efficient program to calculate e^x:

The  e^x is commonly defined by the following power series (Taylor Series).

e^x = 1 + x/1! + x^2/2! + x^3/3! + .......

We can write the above mentioned series in below format,

e^x  = 1 + x/1 + xx/(1*2) +  xxx/(1*2*3) + xxxx/(1*2*3*4) + ..... .

 

In general by definition of the factorial.

x^n = x^(n-1)*x 

n!=(n-1)!*n

So,

x^n/n! => x^(n-1)*x/((n-1)!*n) => [x^(n-1)/(n-1)!] * (x/n)

 

 

Recommended Post:

Leave a Reply

Your email address will not be published. Required fields are marked *