log1p() Function
The log1p() function computes the natural logarithm of one plus a given value. It is particularly useful when working with very small values since it can provide greater accuracy compared to computing log(1+x) directly.
Syntax of log1p()
double log1p(double x);
float log1pf(float x);
long double log1pl(long double x);
Parameters
| Parameter | Description |
|---|---|
x | The value for which the logarithm of (1 + x) is computed. If x is less than -1, a domain error occurs. |
It is worth noting that for very small values of x, log1p() is more accurate than computing log(1+x) directly. Furthermore, when x is less than -1 or equal to -1, errors such as domain or pole errors may occur. Depending on the error handling mode set (via math_errhandling), these errors will either set the global variable errno or raise floating-point exceptions.
Examples for log1p()
Example 1: Calculating the Natural Logarithm for a Positive Value
This example demonstrates how to use log1p() to calculate the natural logarithm of 1 plus a positive value.
Program
#include <stdio.h>
#include <math.h>
int main() {
double value = 0.5;
double result = log1p(value);
printf("Natural logarithm of (1 + %.2f) is %.8f\n", value, result);
return 0;
}
Explanation:
- The program initializes a variable with the value
0.5. - It calls
log1p()to compute the natural logarithm of1 + 0.5. - The result is printed with a precision of 8 decimal places.
Program Output:
Natural logarithm of (1 + 0.50) is 0.40546511
Example 2: Handling Small Magnitude Values for Enhanced Accuracy
This example demonstrates the use of log1p() when working with a very small value, ensuring enhanced precision compared to direct computation.
Program
#include <stdio.h>
#include <math.h>
int main() {
double smallValue = 1e-8;
double result = log1p(smallValue);
printf("Natural logarithm of (1 + %.8f) is %.8f\n", smallValue, result);
return 0;
}
Explanation:
- A very small value (
1e-8) is assigned to a variable. log1p()is used to calculate the logarithm of1 + 1e-8, ensuring better accuracy.- The computed result is printed with high precision.
Program Output:
Natural logarithm of (1 + 0.00000001) is 0.00000001
