log1p() function in PHP

The log1p() function in PHP returns log(1+number), computed in a way that is accurate even when the value of number is close to zero. This function is particularly useful for mathematical calculations involving logarithms of values near zero, where direct calculation of log(1+x) might lose precision.

Syntax

log1p(number)

Parameters

  • number − The numeric value to be processed. Must be greater than -1.

Return Value

Returns the natural logarithm of (1 + number) as a float. If the number is less than or equal to -1, the function returns NAN (Not a Number).

Example 1: Basic Usage

Here's a simple example demonstrating the log1p() function ?

<?php
    echo log1p(1);
    echo "<br>";
    echo log1p(0);
    echo "<br>";
    echo log1p(0.5);
?>
0.69314718055995
0
0.40546510810816

Example 2: Multiple Values

Let us see how log1p() works with different numeric values ?

<?php
    echo "log1p(10): " . log1p(10) . "<br>";
    echo "log1p(2.7): " . log1p(2.7) . "<br>";
    echo "log1p(-0.5): " . log1p(-0.5) . "<br>";
?>
log1p(10): 2.3978952727984
log1p(2.7): 1.3083328196502
log1p(-0.5): -0.69314718055995

Why Use log1p()?

The log1p() function provides better numerical accuracy than log(1+x) when x is close to zero, avoiding floating-point precision issues that can occur with direct calculation.

Conclusion

The log1p() function is essential for precise logarithmic calculations, especially when dealing with small values near zero. It ensures numerical accuracy where standard logarithm functions might fail due to floating-point limitations.

Updated on: 2026-03-15T07:28:47+05:30

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements