Search code examples
javamathlogarithm

Compute Logarithm


I'm trying to write a method that takes in a base k and a value n to 2 decimal places, then computes the log base k of n without using any of Java's Math.log methods. Here's what I have so far:

public static double log(double k, double n) {
    double value = 0.0;

    for(double i = 1; i > .001; i /= 10) {
        while(!(Math.pow(k, value) >= n )) {
            value += i;
        }
    }

    return value;
}

The problem comes up when I try computing log base 4 of 5.0625, which returns 2.0, but should return 1.5.

I have no idea why this isn't working. Any help is appreciated.

No this is not homework, it's part of a problem set that I'm trying to solve for fun.


Solution

  • You're adding the amount i once too ofter. Thus you'll quite soon reach a value larger than the actual value and the while loop will never be entered again.

    Subtract i once from the value and you'll be fine:

    for(double i = 1; i > .001; i /= 10) {
        while(!(Math.pow(k, value) > n )) {
            value += i;
        }
        value -= i;
    }