0

For calculating Log base 2 values with up to 2 decimal values and not floor of Log base 2 values

My Flawed Solution:

static double logbase2(double x) {// It calculates Log base 2 n
        if(x<=1)
            return 0;
        else
            return 1+logbase2(x/2);
    }

I want Log value of up to 2 decimal points so please give pointers

When I am trying, I am always getting floor values.

Gaël J
  • 11,274
  • 4
  • 17
  • 32
No_ven
  • 1
  • 2
  • You seem to mix 2 questions in 1: Why are you getting a StackOverflowError with large input? and: Why are you only getting integer (floored) results? Please pick one and only one. – Sören Jan 08 '23 at 18:12
  • The algorithm you've written doesn't include any fractional values, so what would you expect? (You will probably be best off starting from `Math.log`.) – Louis Wasserman Jan 08 '23 at 19:19

1 Answers1

0

To avoid the stack overflow error with large input you would have to rewrite it to a loop. For example using a while loop:

    static double logbase2(double x) {
        double acc = 0;
        double temp = x;
        while (temp > 1) {
            temp /= 2;
            acc += 1;
        }
        return acc;
    }

JVM does not support the tail call optimisation unfortunately (although in scala or kotlin you can write recursive functions with tail calls and during the compilation those will be rewritten to loops). If a a TCO would work in Java you would be able to write something like this:

    static double logbase2Acc(double x, double acc) {// It calculates Log base 2 n
        if (x <= 1)
            return acc;
        else
            return logbase2Acc(x / 2, acc + 1);
    }
Pavel
  • 785
  • 5
  • 14