The exp()
function in the C programming language, provided through the math.h
header, calculates the base-e exponential of a given number. This function is pivotal in scientific computing, financial calculations, and anywhere exponential growth or decay factors into an algorithm.
In this article, you will learn how to effectively utilize the exp()
function in various programming scenarios. Discover how this function can be applied across different contexts to compute exponential values efficiently and accurately.
Recognize that exp()
computes the exponential of a number with base e, which is approximately 2.71828.
Note that the prototype of exp()
found in math.h
is as follows:
double exp(double x);
This function takes a double precision floating-point number and returns the exponent of e
raised to the power of this number.
Include the math.h
header to access the exp()
function in your C program.
Prepare a double value and use exp()
to calculate its exponential.
#include <stdio.h>
#include <math.h>
int main() {
double value = 1.0;
double result = exp(value);
printf("e^1.0 = %f\n", result);
return 0;
}
In this code, exp()
calculates the exponential of 1.0
, which is the base e
. The result is printed on the console.
Understand that the formula for continuous compounding can be expressed using the exponential function: ( A = P e^{rt} ), where:
Implement the formula using exp()
in a C program.
#include <stdio.h>
#include <math.h>
int main() {
double principal = 1000; // Initial investment
double rate = 0.05; // Annual interest rate
double time = 10; // Time in years
double amount = principal * exp(rate * time);
printf("Amount after %f years is %f\n", time, amount);
return 0;
}
This snippet calculates the amount accumulated over 10 years with a 5% interest rate compounded continuously.
Learn that exponential decay models often use the exp()
function to describe the decrease in quantity over time.
Code a C function simulating exponential decay.
#include <stdio.h>
#include <math.h>
int main() {
double initialAmount = 1000; // Initial quantity
double decayRate = 0.3; // Decay rate
double time = 5; // Time
double remainingAmount = initialAmount * exp(-decayRate * time);
printf("Remaining amount after %f years is %f\n", time, remainingAmount);
return 0;
}
Here, exp()
is used to model the decay of a quantity over 5 years with a decay rate of 0.3 per year.
The exp()
function in C, accessible through math.h
, is an indispensable tool for computing exponential values swiftly and precisely. Whether you are modelling financial forecasts, natural decay processes, or any scenario where exponential change is a factor, exp()
offers a reliable and straightforward solution. By integrating the examples provided, enhance your programs to handle complex calculations with ease and efficiency.