Calculate logarithm value example shows how to calculate natural logarithm values using the log method of Java Math class.
How to calculate natural logarithm value in Java?
We can use the static log
method of the Math class to calculate logarithm values in Java.
1 |
public static double log(double x) |
This method returns the natural logarithm value (base e) of the argument double number.
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.javacodeexamples.mathexamples; public class FindNaturalLogExample { public static void main(String[] args){ double d = 3; System.out.println("Natural Logarithm value is: " + Math.log(d)); } } |
Output
1 |
Natural Logarithm value is: 1.0986122886681098 |
How to calculate log value base 10 in Java?
Thelog
method of the Math class uses base e
. If you want to calculate log base 10 use the following code.
a) Java version 1.4 and below
1 2 3 4 |
double number = 5; double logValue = Math.log(number) / Math.log(10); System.out.println("Log base 10 is: " + logValue); |
Output
1 |
Log base 10 is: 0.6989700043360187 |
b) Java version 1.5 and above
Java version 1.5 introduced a new method log10
which calculates log value using base 10.
1 2 3 4 |
double number = 5; double logValue = Math.log10(number); System.out.println("Log base 10 is: " + logValue); |
Output
1 |
Log base 10 is: 0.6989700043360187 |
How to calculate log value base 2?
Use the following code to calculate log value base 2 in Java.
1 2 3 4 |
double number = 20; double logValue = Math.log(number) / Math.log(2); System.out.println("Log value base 2 is: " + logValue); |
Output
1 |
Log value base 2 is: 4.321928094887363 |
This example is a part of the Java Math class tutorial with examples.
Please let me know your views in the comments section below.