Raising a Number to a Power in Java

Raising a number to a power in Java

^ in java does not mean to raise to a power. It means XOR.

You can use java's Math.pow()


And you might want to consider using double instead of int—that is:

double height;
double weight;

Note that 199/100 evaluates to 1.

Calculating powers of integers

Integers are only 32 bits. This means that its max value is 2^31 -1. As you see, for very small numbers, you quickly have a result which can't be represented by an integer anymore. That's why Math.pow uses double.

If you want arbitrary integer precision, use BigInteger.pow. But it's of course less efficient.

How to make a number to the power of a variable

You need public static double Math.pow(double a, double b):

http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#pow%28double,%20double%29

The ^ is an XOR logic operator in Java.

Raising number to fractional power java

3/7 is evaluated to 0, since you are dividing two integers, so Math.pow(num, pow) becomes Math.pow(num, 0.0) which is 1.0.

Change it to 3.0/7 in order to get a floating point result.

Get the number of digits of a power of 2, with large exponents?

The fastest answer is to use math.
The number of digits in 2^n is (nlog₁₀2)+1 .
You can achieve that by simply returning n * Math.log10(2) + 1. Good luck.



Related Topics



Leave a reply



Submit