C++ log1p()

The log1p() function in C++ takes an argument x and returns the natural logarithm (base-e logarithm) of x+1.

The function is defined in <cmath> header file.

[Mathematics] loge(x+1) = log1p(x) [In C++ Programming]

log1p() prototype [As of C++ 11 standard]

double log1p (double x);
float log1p (float x);
long double log1p (long double x);
double log1p (T x); // For integral type

The log1p() function takes a single argument and returns a value of type double, float or long double.


log1p() Parameters

The log1p() function takes a single mandatory argument in the range [-1, ∞].

If the value is less than -1, log1p() returns Nan (Not a Number).


log1p() Return value

The log1p() function returns the natural logarithm of one plus the given argument.

log1p() return values
Parameter (x) Return Value
x > 0 Positive
x = 0 Zero
-1 > x > 0 Negative
x = -1 -∞ (- infinity)
x < -1 NaN (Not a number)

Example 1: How log1p() function works in C++?

#include <iostream>
#include <cmath>

using namespace std;

int main ()
{
	double x = 21.371, result;

	result = log1p(x);
	cout << "log1p(x) = " << result << endl;

	return 0;
}

When you run the program, the output will be:

log1p(x) = 3.10777

Example 2: log1p() function with integral type

#include <iostream>
#include <cmath>

using namespace std;

int main ()
{
	double result;
	int x = 147;

	result = log1p(x);
	cout << "log1p(x) = " << result << endl;

	return 0;
}

When you run the program, the output will be:

log1p(x) = 4.99721
Did you find this article helpful?