Related Tags

c
c++

# What is log1p in C++?

Samia Ishaque

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

## Overview

The log1p()﻿ function in C++ is defined in the <cmath> header file. log1p() takes an argument x of type double as input and returns the natural logarithm of 1+x.The returned value is equivalent to the following in mathematical notation:

$log_{e}$(x+1)

The function is defined in the C++ <cmath> header file as:

double log1p (double x);


Below is an example of how ﻿to use the log1p() function:

#include <iostream>#include <cmath>using namespace std;int main() {  // your code goes here  double x = 0.2;  cout<<"The natural logarithm for "<<1+x<<" is ";  cout<<log1p(x)<<endl;  return 0;}

Now, let’s perform the same calculations using ﻿the log(x+1) function to compare the return values of the two functions. The following code demonstrates that both methods give us similar results:

#include <iostream>#include <cmath>using namespace std;int main() {  // your code goes here  double x = 0.2;  cout<<"The natural logarithm for "<<1+x<<" is ";  cout<<log(x+1)<<endl;  return 0;}

## Examples

It is important to note the following pointers on what kind﻿s of input parameters the log1p() function ﻿allows:

1. If we pass the parameter 0, the return value will also be 0.

2. If we pass parameter -1, the return value will be $\infty$.

3. When passing a parameter below -1, the return value is NaN ( Not a Number)

4. Only values greater than -1 produce a legitimate result.

The following code demonstrates these input values and their return values:

#include <iostream>#include <cmath>using namespace std;int main() {  // your code goes here  cout<<"The natural logarithm for x=0 is: ";  cout<<log1p(0)<<endl;  cout<<"The natural logarithm for x>0 is: ";  cout<<log1p(1)<<endl;  cout<<"The natural logarithm for x=-1 is: ";  cout<<log1p(-1)<<endl;  cout<<"The natural logarithm for 0<x<-1 is: ";  cout<<log1p(-0.2)<<endl;  return 0;}

RELATED TAGS

c
c++

CONTRIBUTOR

Samia Ishaque