by Neal R. Wagner
Copyright © 2002 by Neal R. Wagner. All rights reserved.
NOTE: This site is obsolete. See book draft (in PDF):
Java supplies a function to calculate natural logs, base e = 2.718281828459045. To calculate logs to other bases, you need to multiply by a fixed constant: for a log base b multiply by 1/logeb
// Logs.java: try out logarithm formulas
public class Logs {
// main function to try out Logs class
public static void main (String[] args) {
System.out.println("log base 2 of 1024 = " + log2(1024));
System.out.println("log base 10 of 1000 = " + log10(1000));
System.out.println("log 2 = " + Math.log(2));
System.out.println("1/log 2 = " + 1/Math.log(2));
System.out.println("log base 10 of 2 = " + log10(2));
} // end of main
// log2: Logarithm base 2
public static double log2(double d) {
return Math.log(d)/Math.log(2.0);
}
// log10: Logarithm base 10
public static double log10(double d) {
return Math.log(d)/Math.log(10.0);
}
}
/* Output:
log base 2 of 1024 = 10.0
log base 10 of 1000 = 2.9999999999999996
log 2 = 0.6931471805599453
1/log 2 = 1.4426950408889634
log base 10 of 2 = 0.30102999566398114
*/