Calculate log2 of a number in Java
This post will discuss how to calculate log2(x) for a number x in Java.
1. Using Math.log() method
The logarithmic identity logba = log10(a)/log10(b) is commonly used to derive log2 for a number x. i.e. log2x = log10(x)/log10(2).
The idea is to use the Math.log() method to find the natural logarithm of a number and then use above logarithmic identity to derive log2(x). Note that for negative numbers, the Math.log() method returns NaN and for zero value, it returns negative infinity.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
public class Main { public static double log2(int x) { return Math.log(x) / Math.log(2); } public static void main(String[] args) { int x = 10; double log2x = log2(x); System.out.println(log2x); // 3.3219280948873626 } } |
2. Using Guava Library
Guava provides the LongMath.log2() method that returns the base-2 logarithm of a number, rounded according to the specified rounding mode.
Its usage is demonstrated below. Note that for non-positive numbers, LongMath.log2() throws java.lang.IllegalArgumentException.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import com.google.common.math.LongMath; import java.math.RoundingMode; public class Main { public static int log2(int x) { return LongMath.log2(x, RoundingMode.FLOOR); } public static void main(String[] args) { int x = 10; int log2x = log2(x); System.out.println(log2x); // 3 } } |
3. Using Integer.numberOfLeadingZeros() method
The idea here is to use the Integer.numberOfLeadingZeros() method to get the count of zero bits preceding the most significant set bit in the binary representation of a number. Then you can get the log2(x) for a number x using the formula: 31 - Integer.numberOfLeadingZeros(x).
This is demonstrated below. Note that for non-positive numbers, the code explicitly throws java.lang.IllegalArgumentException exception.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class Main { public static int log2(int x) { if (x <= 0) { throw new IllegalArgumentException("x (" + x + ") must be positive"); } return 31 - Integer.numberOfLeadingZeros(x); } public static void main(String[] args) { int x = 10; int log2x = log2(x); System.out.println(log2x); // 3 } } |
That’s all about calculating log2(x) for a number x in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)