log1p, log1pf, log1pl

Header: <math.h>

1-3) Computes the natural (base e) logarithm of 1 + arg. This function is more precise than the expression log(1 + arg) if arg is close to zero.

# Declarations

float log1pf( float arg );

(since C99)

double log1p( double arg );

(since C99)

long double log1pl( long double arg );

(since C99)

#define log1p( arg )

(since C99)

# Parameters

# Return value

If no errors occur ln(1 + arg) is returned.

# Notes

The functions expm1 and log1p are useful for financial calculations, for example, when calculating small daily interest rates: (1+x)n-1 can be expressed as expm1(n * log1p(x)). These functions also simplify writing accurate inverse hyperbolic functions.

# Example

#include <errno.h>
#include <fenv.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
// #pragma STDC FENV_ACCESS ON
 
int main(void)
{
    printf("log1p(0) = %f\n", log1p(0));
    printf("Interest earned in 2 days on $100, compounded daily at 1%%\n"
           " on a 30/360 calendar = %f\n",
           100*expm1(2*log1p(0.01/360)));
    printf("log(1+1e-16) = %g, but log1p(1e-16) = %g\n",
           log(1+1e-16), log1p(1e-16));
 
    // special values
    printf("log1p(-0) = %f\n", log1p(-0.0));
    printf("log1p(+Inf) = %f\n", log1p(INFINITY));
 
    // error handling
    errno = 0; feclearexcept(FE_ALL_EXCEPT);
    printf("log1p(-1) = %f\n", log1p(-1));
    if (errno == ERANGE)
        perror("    errno == ERANGE");
    if (fetestexcept(FE_DIVBYZERO))
        puts("    FE_DIVBYZERO raised");
}

# See also