Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: logarithm-algorithm-java

Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: logarithm-algorithm-java
Showing posts with label logarithm-algorithm-java. Show all posts
Showing posts with label logarithm-algorithm-java. Show all posts

Java Taking Logarithms

Java Taking Logarithms

Problem

You need to take the logarithm of a number.

Solution

For logarithms to base e , use java.lang.Math ’s log( ) function:

// Logarithm.java
double someValue;
// compute someValue...
double log_e = Math.log(someValue);

For logarithms to other bases, use the identity that:

                  loge ( x )
                     
logn ( x ) = -------------------
                      loge ( n )

                       

where x is the number whose logarithm you want, n is any desired base, and e is the natural logarithm base. I have a simple LogBase class containing code that imple- ments this functionality:

// LogBase.java
public static double log_base(double base, double value) {
return Math.log(value) / Math.log(base);
}

Explained 

My log_base function allows you to compute logs to any positive base. If you have to perform a lot of logs to the same base, it is more efficient to rewrite the code to cache the log(base) once. Here is an example of using log_base :

// LogBaseUse.java
public static void main(String argv[]) {
double d = LogBase.log_base(10, 10000);
System.out.println("log10(10000) = " + d);
}
C:> java LogBaseUse
log10(10000) = 4.0