IamIC
IamIC

Reputation: 18249

Calculate power with fixed (constant) exponent

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.

Upvotes: 1

Views: 1194

Answers (4)

user1770305
user1770305

Reputation: 101

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.

Upvotes: 1

alestanis
alestanis

Reputation: 21863

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.

Upvotes: 0

Ionut Hulub
Ionut Hulub

Reputation: 6326

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.

Upvotes: 3

Barranka
Barranka

Reputation: 21047

Remember this equiality:

x^y = exp(y * ln(x))

So you can skip Pow and use exp and ln.

Upvotes: 3

Related Questions