C++ Math log
The function is utilized to determine the natural logarithm (ln) of a specified number.
Mathematically:
Suppose 'x' is a given number:
logex = log(x);
Syntax
float log(float x);
double log(double x);
long double log(long double x);
double log(integral x);
Parameter
x : This represents the value for which we want to find the natural logarithm.
Return value
Below are the outcomes produced by a specified numerical input:
| Parameter(x) | Return value |
|---|---|
x>1 |
Positive |
x=1 |
0 |
| 1>x>0 | Negative |
x=0 |
-infinty |
x<0 |
Not a Number(nan) |
Example 1
Let's examine a basic scenario where the value assigned to x is 1.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int x=1;
std::cout << "Value of x is : " <<x <<std::endl;
cout<<"Log value of x is : "<<log(x);
return 0;
}
Output:
Value of x is : 1
Log value of x is : 0
In this instance, the variable x is set to 1. Consequently, the log function yields the absolute value which is 0.
Example 2
Let's see another simple example
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int x=3;
std::cout << "Value of x is : " <<x <<std::endl;
cout<<"Log value of x is : "<<log(x);
return 0;
}
Output:
Value of x is : 3
Log value of x is : 1.09861
In this instance, the variable x is assigned a value of 3. Consequently, the log function will yield a positive result, specifically 1.09861.
Example 3
Let's consider a basic scenario where the value assigned to x is -0.5.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
float x= -0.5;
std::cout << "Value of x is : " <<x <<std::endl;
cout<<"Log value of x is : "<<log(x);
return 0;
}
Output:
Value of x is : -0.5
Log value of x is : nan
In this instance, when x is set to -0.5, the log function will yield a result of Not a Number (nan).
Example 4
Let's examine a basic scenario where the value of x equals 0.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int x= 0;
std::cout << "Value of x is : " <<x <<std::endl;
cout<<"Log value of x is : "<<log(x);
return 0;
}
Output:
clValue of x is : 0
Log value of x is : -inf
In this instance, the value assigned to x is -1. Consequently, the log function yields nan(Not a Number).
Example 5
Let's examine a basic scenario where the value assigned to x is 0.8.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
float x=0.8;
std::cout << "Value of x is : " <<x <<std::endl;
cout<<"Log value of x is : "<<log(x);
return 0;
}
Output:
Value of x is : 0.8
Log value of x is : -0.223144
In this instance, the value assigned to x is 0.8. Consequently, the log function yields a negative result, specifically -0.22.