Java - Math log() Method



Description

The Java Math log(double a) returns the natural logarithm (base e) of a double value. Special cases:

  • If the argument is NaN or less than zero, then the result is NaN.

  • If the argument is positive infinity, then the result is positive infinity.

  • If the argument is positive zero or negative zero, then the result is negative infinity.

Syntax

public static double log(double d)

Parameters

Here is the detail of parameters −

  • d − Any primitive data type.

Return Value

  • This method returns the natural logarithm of the argument.

Example 1

In this example, we're showing the usage of Math.log() method to get the log of a double number. We've created two double variables x, y and initialized them with different values. Then using Math.log() method we're printing the log of a double value.

public class Test { 
   public static void main(String args[]) {
      double x = 11.635;
      double y = 2.76;

      System.out.printf("The value of e is %.4f%n", Math.E);
      System.out.printf("log(%.3f) is %.3f%n", x, Math.log(x));  
   }
}

This will produce the following result −

Output

The value of e is 2.7183
log(11.635) is 2.454

Example 2

In this example, we're showing the usage of Math.log() method to get the log of a float number. We've created two float variables x, y and initialized them with different values. Then using Math.log() method we're printing the log of a float value.

public class Test { 
   public static void main(String args[]) {
      float x = (float)11.635;
      float y = (float)2.76;

      System.out.printf("The value of e is %.4f%n", Math.E);
      System.out.printf("log(%.3f) is %.3f%n", x, Math.log(x));  
   }
}

This will produce the following result −

Output

The value of e is 2.7183
log(11.635) is 2.454

Example 3

In this example, we're showing the usage of Math.log() method to get the log of zero. We've created a double variable and initialized it with 0.0. Then using Math.log() method we're printing the log of a zero value.

public class Test { 
   public static void main(String args[]) {
      double x = 0.0;

      System.out.printf("The value of e is %.4f%n", Math.E);
      System.out.printf("log(%.3f) is %.3f%n", x, Math.log(x));  
   }
}

This will produce the following result −

Output

The value of e is 2.7183
log(0.000) is -Infinity
java_numbers.htm
Advertisements