-2

Wondering what is the right way to represent x^(1/3)? Here is my code and it returns right value 2 for 8^(1/3). Wondering if any other better methods?

int a = 8;
System.out.println(Math.pow(8, 1/3.0)); // returns 2

regards, Lin

Lin Ma
  • 9,739
  • 32
  • 105
  • 175

1 Answers1

6

There is a Math.cbrt method for x1/3.

System.out.println(Math.cbrt(8));

See also:

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 2
    Ah, the cube root (horrible method name) – Ole V.V. Mar 15 '17 at 23:30
  • Thanks kennytm, if for any root, not necessarily to be cube root, is there a general function (e.g. for n ^ (1/m))? – Lin Ma Mar 16 '17 at 00:28
  • 1
    @LinMa No there isn't. Use `Math.pow(x, 1/n)` as you have written, or the implementation by the asker of the second linked question if you want to deal with odd roots of negative numbers as well. – kennytm Mar 16 '17 at 01:00
  • Thanks kennytm for the confirm, mark your reply as answer. – Lin Ma Mar 16 '17 at 06:12