Search code examples
javafloating-pointdivisionexponentiation

How to calculate a^(1/n)?


I am trying to calculate a^(1/n), where ^ denotes exponentiation.

However, the following:

Math.pow(8, 1/3)

returns 1.0 instead of returning 2.0.

Why is that?


Solution

  • The problem is that 1/3 uses integer (truncating) division, the result of which is zero. Change your code to

    Math.pow(8, 1./3);
    

    (The . turns the 1. into a floating-point literal.)