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:
(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 heredouble 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 heredouble x = 0.2;cout<<"The natural logarithm for "<<1+x<<" is ";cout<<log(x+1)<<endl;return 0;}
It is important to note the following pointers on what kinds of input parameters the log1p()
function allows:
If we pass the parameter 0, the return value will also be 0.
If we pass parameter -1, the return value will be .
When passing a parameter below -1, the return value is NaN ( Not a Number)
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 herecout<<"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;}
Free Resources