Calculate power with fixed (constant) exponent
Domanda
I have a case where I need to calculate x^y a vast number of times where y is a constant and x is guaranteed to be a valid number.
How can this be done more efficiently that Pow(double x, double y), which will perform various checks and evaluations?
I am looking to precalculate the y transformation.
EDIT
Both are real numbers. x = 0 ... 4,000,000,000.
Soluzione
Remember this equiality:
x^y = exp(y * ln(x))
So you can skip Pow
and use exp
and ln
.
Altri suggerimenti
You cannot. Although y is a constant, x is a variable so there is nothing you can do. I wouldn't worry about it though. the pow() method is very well optimized.
The only thing you can do is to pre calculate the values for many different x's, and save them in a dictionary, unless they can get really big.
There is no faster way in java, since it doesn't support vector operations or at least has a hard time optimizing the code to use them because there a no good parallel annotations.
You should probably try to use a native libary and call it with JNI.
If you know y
, maybe you can decompose it into a multiplication of smaller numbers, and compute powers of powers. For instance, if y = 6
you could do
y = 2 * 3
power = pow( pow(x, 3), 2)
Don't know if it will be faster though.