C++ Math log2
The function computes the base 2 logarithm of a given 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 whose logarithm is to be calculated.
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 see the simple example when the value of x is greater than 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 example, log2 function computes the logarithm value of base 2 when the value of x is greater than one
Example 2
Let's see the simple example when the value of x is equal to 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 example, log2 function computes the logarithm value of base 2 when the value of x is equal to one.
Example 3
Let's see the simple example when the value of x lies between 0 and 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 example, log2 function computes the logarithm value of base 2 when the value of x is equal to 0.2.
Example 4
Let's see the simple example when the value of x is equal to 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 example, log2 function computes the logarithm value of base 2 when the value of x is equal to 0.
Example 5
Let's see the simple example when the value of x is less than zero.
#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 example, log2 function computes the logarithm value of base 2 when the value of x is less than zero.