C++ Math log2
The function calculates the binary logarithm of a specified number.
Suppose a number is 'x':
log2(x) = log2x;
Syntax
float log2(float x);
double log2(double x);
long double log2(long double x);
double log2(integral x);
Note: The return_type can be float, double or long double.
Parameter
x : The value for which the logarithm is to be computed.
Return value
| Parameter | Return value |
|---|---|
x>1 |
Positive |
x=1 |
Zero |
| 1>x> 0 | Negative |
| x= 0 | -infinity |
x<0 |
Not a Number(nan) |
Example 1
Let's consider a basic scenario where the value of x exceeds one.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int x=2;
std::cout << "Value of x is : " <<x <<std::endl;
cout<<"log2(x) = "<<log2(x);
return 0;}
Output:
Value of x is : 2
log2(x) = 1
In this instance, the log2 function calculates the logarithmic value with a base of 2 for x values exceeding one.
Example 2
Let's consider a straightforward scenario where the value assigned to variable 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<<"log2(x) = "<<log2(x);
return 0;
}.
Output:
Value of x is : 1
log2(x) = 0
In this instance, the log2 function calculates the logarithm with a base of 2 given the input x equals one.
Example 3
Let's consider a straightforward scenario where the value of x falls within the range of 0 to 1.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
float x=0.2;
std::cout << "Value of x is : " <<x <<std::endl;
cout<<"log2(x) = "<<log2(x);
return 0;
}
Output:
Value of x is : 0.2
log2(x) = -2.32193
In this instance, the log2 function calculates the logarithmic value with a base of 2 for x = 0.2.
Example 4
Let's examine a basic scenario where the value of x equals zero.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int x=0;
std::cout << "Value of x is : " <<x <<std::endl;
cout<<"log2(x) = "<<log2(x);
return 0;
}
Output:
Value of x is : 0
log2(x) = -inf
In this instance, the log2 function calculates the logarithmic value with a base of 2 for x when x equals 0.
Example 5
Let's consider a basic scenario where the value of x is negative.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
float x= -1.50;
std::cout << "Value of x is : " <<x <<std::endl;
cout<<"log2(x) = "<<log2(x);
return 0;
}
Output:
Value of x is : -1.5
log2(x) = nan
In this instance, the log2 function calculates the logarithm value with a base of 2 for x values below zero.