3

I want to calculate x power y and both x,y are double values. Why is java giving me a compilation error? What is the best way to do so?

I am currently using the following method:

x^y // attempt to calculate (x pow y)

Thanks.

chollida
  • 7,834
  • 11
  • 55
  • 85
user378101
  • 649
  • 3
  • 12
  • 19
  • 5
    You mentioned compilation error. In case you tried `x ^ y`, you should know that `^` in Java is _NOT_ an exponentiation operator. http://stackoverflow.com/questions/1991380/what-does-the-operator-do-in-java/2672217#2672217 – polygenelubricants Jul 16 '10 at 08:08

6 Answers6

8
Math.pow(x, y);

Read the java.lang.Math docs.

Yuval Adam
  • 161,610
  • 92
  • 305
  • 395
2

The simplest way to implement it remains, as always:

Take the logarithm (base 10) of x; multiply it by y, and take the inverse logarithm (base 10) of the result to get x pow y.

To simply calculate it, Math.pow(x,y);, as has been pointed out.

Williham Totland
  • 28,471
  • 6
  • 52
  • 68
1
Math.pow(x,y);

example:

Math.pow(2.23, 3.45);
Sadat
  • 3,493
  • 2
  • 30
  • 45
1
        Math.pow(a, b);
Manuel Selva
  • 18,554
  • 22
  • 89
  • 134
1

See the Math class. It has a static function pow, which accepts double values as arguments.

Bozhidar Batsov
  • 55,802
  • 13
  • 100
  • 117
1
    Double a = 3.0;
    Double b = 2.0;
    assert Math.pow(a, b) == 9.0;
Noel M
  • 15,812
  • 8
  • 39
  • 47