exp() Function
The exp()
function in C computes the base‑e exponential value of a given number. It calculates the result of raising e to the power of the provided value. This function is commonly used in various mathematical and scientific computations involving growth, decay, and logarithmic transformations.
Syntax of exp()
double exp(double x);
Parameters
Parameter | Description |
---|---|
x | The exponent value for which the exponential function is computed. |
Return Value
The function returns the computed exponential value. If the result is too large to be represented, it returns HUGE_VAL
(or its float or long double equivalents) and an overflow error occurs.
It is important to note that if the magnitude of the result exceeds the representable range, an overflow condition will be signaled by returning HUGE_VAL
, making error handling essential when working with large exponents.
Examples for exp()
Example 1: Basic Calculation of Exponential Function
This example demonstrates how to calculate the exponential value of a positive number using exp()
.
Program
#include <stdio.h>
#include <math.h>
int main() {
double x = 2.0;
double result = exp(x);
printf("exp(%.1f) = %f\n", x, result);
return 0;
}
Explanation:
- Set the exponent value to 2.0.
- Call the
exp()
function to compute e raised to the power 2.0. - Print the computed exponential value using
printf()
.
Program Output:
exp(2.0) = 7.389056
Example 2: Calculating Exponential for a Negative Number
This example shows how to compute the exponential of a negative number, resulting in a fractional output.
Program
#include <stdio.h>
#include <math.h>
int main() {
double x = -1.0;
double result = exp(x);
printf("exp(%.1f) = %f\n", x, result);
return 0;
}
Explanation:
- Assign the exponent value as -1.0.
- Invoke
exp()
to compute the exponential of -1.0. - Display the resulting fractional value using
printf()
.
Program Output:
exp(-1.0) = 0.367879
Example 3: Managing Overflow with a Large Exponent
This example illustrates the behavior of the exp()
function when provided with a very large exponent value that can cause an overflow.
Program
#include <stdio.h>
#include <math.h>
int main() {
double x = 1000.0;
double result = exp(x);
if(result == HUGE_VAL) {
printf("Overflow occurred: result is HUGE_VAL\n");
} else {
printf("exp(%.1f) = %f\n", x, result);
}
return 0;
}
Explanation:
- Assign a very large value (1000.0) to trigger potential overflow.
- Call
exp()
to compute the exponential of the large value. - Check if the returned result equals
HUGE_VAL
to detect overflow. - Print an appropriate message indicating that an overflow has occurred.
Program Output:
Overflow occurred: result is HUGE_VAL