Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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:

Solution

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 implements this functionality:

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

Discussion

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); 
} 
log10(10000) = 4.0
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata