Search code examples
javamathpowexponentiation

Squaring Numbers in java using Math.pow getting error of precision


I have do to a question to write a method to input an array of type LONG that stores the values of all the powers of 2 from 0 to 63 (i.e. 20 to 263)

Output the contects of the array screen. Hint: Math.pow(x,y) is ued to put number x to exponent y

so far I have something like

I keep getting error or Math.pow(size,2); required long, found double. I tried Math.pow(i,2); I get same error./ possible loss of precision ,, any help :) thanks

class ws3q2
{
    public static void main(String[]args)
    {

        int ARRAY_SIZE = 5;

        long size = ARRAY_SIZE;

        long[] array = new long[ARRAY_SIZE];

        for(int i = 0; i < ARRAY_SIZE; ++i)
        {
        array[i] = Math.pow(size,2);
        }

    }
}

Solution

  • Better shift

    For 2x where x ∈ ℕ, you are better off writing this as a bit shift

    1L << x
    

    instead of a floating point exponentiation

    pow(2, x)
    

    both in terms of precision and in terms of performance. In fact, 1L << x is so easy to compute that I'd prefer writing that instead of array[x], so you might perhaps avoid the array altogether.

    More errors?

    pow(x, 2) as you write in your code would be x2 which you could compute more easily as x*x. So which one is it to be, powers of two or squares?

    Furthermore, you write pow(size,2) which uses size and does not depend on i. So all values of your array would be equal. I guess that is not what you meant.

    Where your error comes from

    The reason of the error message is the fact that the result of Math.pow is double, and implicit conversion from double to long is forbidden in Java. You'd have to write an explicit cast, i.e. (long)pow(2, x). But that does round towards zero, so a slight numeric error might cause a wrong result. The only exactness guarantee you have for Math.pow is this:

    The computed result must be within 1 ulp of the exact result.

    You could add 0.5 before doing the conversion, or use Math.round instead of the cast, but as you see, you have to know a lot about the internal workings of floating point math to get this correct. Better to stick to integer math and avoid double and Math.pow altogether.