Reputation: 421
I'm trying to write a Java program that can take values and put them into a formula involving log 1/3.
How can I calculate log 1/3 in Java?
Upvotes: 6
Views: 42037
Reputation: 2777
1/3 yields the result as integer type value. So, the result will be 0, not 0.3333.
Therefore, Math.log(1/3) = Math.log(0), which results in infinity.
So, you need to write Math.log(1/3.0) to get the desired result.
Upvotes: 3
Reputation: 33993
You can calculate the natural logarithm using the Java.lang.Math.log() method:
System.out.println("Math.log(1/3.0)=" + Math.log(1/3.0));
See http://www.tutorialspoint.com/java/lang/math_log.htm and http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#log%28double%29
In order to get the log_10 you can do it as follows:
System.out.println("log_10(1/3.0)=" + (Math.log(1/3.0)/Math.log(10)));
Upvotes: 1
Reputation: 4620
When you want to calculate the logarithm you need to know the base. Once you know the base you can perform the calculation:
log_b(x) = ln(x) / ln(b)
http://en.wikipedia.org/wiki/Logarithm#Change_of_base
In Java the Math#log(double) function calculates the natural logarithm. So you can use this to calculate the logarithm to a given base b:
double result = Math.log(x) / Math.log(b);
Upvotes: 8
Reputation: 22974
You can use Math.log(value)
to get log of specific value where value is considered to be in double
.You can also use Math.log10(value)
to get base 10 log.
So you can just use
Math.log(1/3.0)
Upvotes: 7
Reputation: 35547
You don't need a new implementation there is inbuilt function for this
Read about Math.log()
But in this case log(1/3)
will give you value as infinity
,If you use Math.log(1/3)
.
You can use log
rule as follows.
log(1/3) =log(1)-log(3)
Now
Math.log(1/3)=Math.log(1)-Math.log(3)
Eg:
System.out.println(Math.log(1)-Math.log(3));
Out put:
-1.0986122886681098
Upvotes: 0