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()

</>
Copy
double exp(double x);

Parameters

ParameterDescription
xThe 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

</>
Copy
#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:

  1. Set the exponent value to 2.0.
  2. Call the exp() function to compute e raised to the power 2.0.
  3. 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

</>
Copy
#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:

  1. Assign the exponent value as -1.0.
  2. Invoke exp() to compute the exponential of -1.0.
  3. 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

</>
Copy
#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:

  1. Assign a very large value (1000.0) to trigger potential overflow.
  2. Call exp() to compute the exponential of the large value.
  3. Check if the returned result equals HUGE_VAL to detect overflow.
  4. Print an appropriate message indicating that an overflow has occurred.

Program Output:

Overflow occurred: result is HUGE_VAL