how to use logarithm function in java with example

logarithm function can be used in java using math class method

1. Natural logarithm in java

Syntax:-

Math.log(variable)

variable must be double datatype.

log method used to find natural logarithm (base e) of a variable

Math.log(2) = 0.6931471805599453

2. base 10 logarithm in java

Syntax:-

Math.log10(variable)

variable must be double datatype.

log method used to find base 10 logarithm of a variable

Math.log10(2) = 0.3010299956639812

3. base 10 logarithm in java

Syntax:-

Math.log1p(variable)

variable must be double datatype.

Here 1 is added to the variable than take natural logarithm of that sum. ie log(variable+1)

Math.log1p(2) = 1.0986122886681096

Note:-
# If the variable is NaN or less than zero, then the result is NaN.
# If the variable is positive infinity, then the result is positive infinity.
# If the variable is positive zero or negative zero, then the result is negative infinity.
# The computed result must be within 1 ulp of the exact result. Results must be semi-monotonic.

Example:-

import java.util.Scanner;

class group{
public static void main(String angt[]){
Scanner data = new Scanner(System.in);
double num,num1;
System.out.println("Enter a number");
num1=data.nextDouble();

num=Math.log(num1);
System.out.println("log Answer:"+num);

num=Math.log10(num1);
System.out.println("log10 Answer:"+num);

num=Math.log1p(num1);
System.out.println("log1p Answer:"+num);


}
}

Output:-

Enter a number
3
log Answer:1.0986122886681098
log10 Answer:0.47712125471966244
log1p Answer:1.3862943611198906



Previous Code:-

List Code:-

Next Code:-

Java Programs:-

Leave reply

Add your comments here

Back to Top