log() Function
The log()
function computes the natural logarithm, which is the inverse of the natural exponential function. It calculates the logarithm with base-e for a given value. This function is commonly used in mathematical computations where natural logarithms are required.
Syntax of log()
double log(double x);
float logf(float x);
long double logl(long double x);
Parameters
Parameter | Description |
---|---|
x | The value whose natural logarithm is to be computed. A domain error occurs if x is negative. In some implementations, a zero value may cause a pole error. |
Return Value
The function returns the natural logarithm of the given value. If an error occurs due to a negative argument or zero (depending on the library), the result may be undefined or trigger a domain/pole error.
Additional Notes
The natural logarithm computed by log()
is the inverse of the exponential function (exp()
). For calculations requiring base-10 logarithms, refer to the log10()
function. Additionally, the header <tgmath.h>
provides a type-generic macro version of this function in C99 and later.
Examples for log()
Example 1: Calculating Natural Logarithm for a Positive Number
This example demonstrates the use of log()
to calculate the natural logarithm of a positive number.
Program
#include <stdio.h>
#include <math.h>
int main() {
double value = 2.71828; // Approximate value of e
double result = log(value);
printf("The natural logarithm of %.5f is %.5f\n", value, result);
return 0;
}
Explanation:
- The variable
value
is initialized with approximately the value of e. - The
log()
function calculates the natural logarithm ofvalue
. - The result is stored in the variable
result
. - The computed natural logarithm is printed to the console.
Program Output:
The natural logarithm of 2.71828 is 1.00000
Example 2: Error Handling with Zero and Negative Inputs
This example shows the behavior of log()
when provided with zero and negative inputs. In many implementations, log(0)
yields negative infinity, while log()
of a negative number results in a domain error (often represented as NaN).
Program
#include <stdio.h>
#include <math.h>
#include <errno.h>
int main() {
double zero = 0.0;
double negative = -10.0;
double logZero = log(zero);
double logNegative = log(negative);
printf("log(0) = %f\n", logZero);
printf("log(-10) = %f\n", logNegative);
return 0;
}
Explanation:
- The variable
zero
is set to 0.0 andnegative
is set to -10.0. - The
log()
function is called with 0.0, which typically returns negative infinity. - The function is also called with a negative value, which leads to a domain error, often resulting in NaN.
- The results are printed to the console, illustrating the error handling behavior.
Program Output:
log(0) = -inf
log(-10) = nan