Exponential and logarithmic functions: exp, log, log10
What you'll learn: How to calculate powers of e and find logarithms using the C standard library.
Growing and shrinking numbers
In scientific programming, we often deal with growth and decay. Whether you are calculating compound interest or measuring the intensity of an earthquake, you need tools to handle exponents and logarithms. The math.h library provides three essential functions for this: exp(), log(), and log10(). All of these functions take a double as an argument and return a double.
The Power of e: exp()
The function exp(x) calculates , where is Euler's number (approximately 2.718). Think of exp() as a "growth machine." If you tell it how much time has passed, it tells you how much something has grown.
Finding the Exponent: log() and log10()
Logarithms are the opposite of exponents; they tell you what power a number was raised to.
log(x): This is the natural logarithm (). It is the inverse ofexp(). Ifexp(1)is , thenlog(e)is 1.log10(x): This is the common logarithm (base 10). This is very intuitive for humans because it essentially counts the number of zeros in a large number. For example,log10(1000)is 3.
A Practical Example
To use these, you must include <math.h> and, on many Linux systems, link the math library using the -lm flag when compiling.
#include <stdio.h>
#include <math.h>
int main() {
double value = 2.0;
// Calculate e raised to the power of 2
double growth = exp(value);
printf("e squared is: %f\n", growth);
// Calculate the natural log of our result (brings us back to 2)
double original = log(growth);
printf("Natural log of growth is: %f\n", original);
// Calculate how many times 10 multiplies into 1000
double powerOfTen = log10(1000.0);
printf("Log10 of 1000 is: %f\n", powerOfTen);
return 0;
}
Watch for the limit
Logarithms have a strict rule: you cannot take the log of a negative number or zero. If you try to pass 0 or -1.0 into log(), your program will return a special value called NaN (Not a Number) or -HUGE_VAL, representing negative infinity. Always ensure your input is positive!
Key takeaway
Use exp(x) for powers of , log(x) for the natural logarithm, and log10(x) for base-10 calculations.