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:
- log2 function in C.
- Use of log10 function in C.
- log function in C.
- fabs use in C language.
- abs labs llabs functions in C/C++.
- floor function in C with example code.
- ceil function use in C programming.
- Use of pow function in C language.
- C program to calculate the power of a number.
- sqrt function in C.
- C program to find all roots of a quadratic equation using switch case.
- C program to find the roots of a quadratic equation.
- How to find whether a given number is prime number in C?
- Use of isxdigit in C programming.
- How to use ispunct function in C programming?