Use Math.pow(double, double), or statically import pow as such:
import static java.lang.Math.pow;
Answer from Stefan Kendall on Stack OverflowVideos
Use Math.pow(double, double), or statically import pow as such:
import static java.lang.Math.pow;
Sure, you just need to call Math.pow(...), as it's a static method in the Math class:
for (int i = 0; i < n; i++) {
functionG[i] = Math.pow(1.25, i);
}
Note that I've changed it to use i rather than n as the second argument.
You could also get your original code to compile using:
import static java.lang.Math.pow;
in the import statements at the top of your code. See the Java Language Specification, section 7.5.3 for details of how this works.
When it's a power of 2 keep in mind that you can use a simple and fast shift expression: 1 << exponent
For example:
22 = 1 << 2 = (int) Math.pow(2, 2)
210 = 1 << 10 = (int) Math.pow(2, 10)
For larger exponents (over 31) use long instead:
232 = 1L << 32 = (long) Math.pow(2, 32)
BTW, in Kotlin you have shl instead of <<:
(Java) 1L << 32 = 1L shl 32 (Kotlin)
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.