MySQL - LOG2() Function



The MySQL LOG2() function accepts a numerical value as a parameter and returns the base-2 logarithm of the given value.

According to the mathematical definition, a logarithmic function of a number produces a result which is raised by its base to achieve the said number. However, in usual logarithms, the base can be any value. But for this method, we only take the base value as 2.

Syntax

Following is the syntax of MySQL LOG2() function −

LOG2(X);

Parameters

This function takes a numeric value as a parameter.

Return Value

This function returns the base-2 logarithm of the given value.

Example

In the following example, we are using the MySQL LOG2() function to calculate the base-2 logarithm of the number 55 −

SELECT LOG2(55) As Result;

Output

This will produce the following result −

Result
5.78135971352466

Example

Following is another example of this function, where we are calculate the base-2 logarithm of the decimal number 567439474.4684 −

SELECT LOG2(567439474.4684) As Result;

Output

The output is displayed as follows −

Result
29.079891275659143

Example

If the value passed to the function is less than or equal to 0.0E0, it returns NULL

SELECT LOG2(0) As Result;

The output for the query above is produced as given below −

Result
NULL

Here, we are passing a value that is less than 0.0E0 −

SELECT LOG2(-6) As Result;

Following is the output −

Result
NULL

Example

You can also pass the numerical value as a string, to this function −

SELECT LOG2('2656') As Result;

Output

The output for the query above is produced as given below −

Result
11.375039431346925

Example

The MySQL LOG2() function is equivalent to LOG(2, X). Following are the examples −

SELECT LOG(2, 44747) As Result;

The output is displayed as follows −

Result
15.449503341698307

Here, we are using the LOG2() function to calculate the base-2 logarithm of the number 44,747 −

SELECT LOG2(44747) As Result;

As we can see the output below, both the LOG2() and LOG(2,X) results are same −

Result
15.449503341698307
Advertisements