EN
Java - Math.log() method example
3 points
The Math.log()
method returns the natural logarithm (base e) of a number.
xxxxxxxxxx
1
public class MathExample {
2
3
public static void main(String[] args) {
4
// Natural logarithm (logarithm with base e):
5
// x y
6
System.out.println( Math.log( 1 ) ); // 0
7
System.out.println( Math.log( 7 ) ); // 1.9459101490553132
8
System.out.println( Math.log( 10 ) ); // 2.3025850929940460
9
System.out.println( Math.log( 100 ) ); // 4.6051701859880920
10
System.out.println( Math.log( 1000 ) ); // 6.9077552789821370
11
12
System.out.println( Math.log( -1 ) ); // NaN
13
System.out.println( Math.log( 0 ) ); // -Infinity
14
System.out.println( Math.log( Double.POSITIVE_INFINITY ) ); // +Infinity
15
16
System.out.println( Math.E ); // 2.718281828459045
17
18
// Logarithm with custom base is placed in below example.
19
}
20
}
The Math.log()
method is presented on the following chart:

Syntax |
xxxxxxxxxx 1 package java.lang; 2 3 public final class Math { 4 5 public static double log(double x) { ... } 6 7 }
|
Parameters | x - double value in the range 0 to +Infinitive (primitive value). |
Result |
If If If |
Description |
|
This example shows a logarithmic function calculation with its own base.
xxxxxxxxxx
1
public class MathExample {
2
3
static double calculateLogarithm(double base, double x) {
4
double a = Math.log(x);
5
double b = Math.log(base);
6
7
return a / b;
8
}
9
10
public static void main(String[] args) {
11
// Logarithm with custom base:
12
// base x y
13
System.out.println( calculateLogarithm( 2, 2 ) ); // 1.0
14
System.out.println( calculateLogarithm( 2, 4 ) ); // 2.0
15
System.out.println( calculateLogarithm( Math.E, Math.E ) ); // 1.0
16
System.out.println( calculateLogarithm( 3, 9 ) ); // 2.0
17
System.out.println( calculateLogarithm( 3, 81 ) ); // 4.0
18
System.out.println( calculateLogarithm( 10, 10 ) ); // 1.0
19
}
20
}