Results 1 to 5 of 5
Thread: Computing a cube (power of 3).
- 01-16-2009, 04:54 PM #1
Member
- Join Date
- Dec 2008
- Posts
- 8
- Rep Power
- 0
Computing a cube (power of 3).
Hello everyone,
I am trying to compute the cube of a bunch of integers, starting from 1 to n.
I am dealing with efficiency and I want to know the fastest way to compute those numbers.
I am currently using x * x * x, rather than Math.pow(x, 3).
I would like to know if my actual solution is the fastest, and if there is any that would be better.
Thank you very much.
- 01-16-2009, 05:02 PM #2
Senior Member
- Join Date
- Jan 2009
- Posts
- 119
- Rep Power
- 0
I am guessing x * x * x would be faster, right?
- 01-16-2009, 05:50 PM #3
Senior Member
- Join Date
- Nov 2008
- Posts
- 286
- Rep Power
- 5
If speed is important, always calculate integer powers with combinations of multiplying the current result by itself or by the original number. So extending the logic:
Not only is it faster, but it turns out to be quite a lot faster. On my Pentium, each multiplication requires 2 clock cycles, but Math.pow() requires up to around 700 clock cycles!Java Code:x^4 : y = x * x; return y * y; x^5 : y = x * x; return y * y * x; x^6 : y = x * x * x; return y * y; ...
So in general, Math.pow() is an extremely slow way of calculating a power if the exponent is known in advance. (And even for an arbitrary integer exponent, there are still faster ways of doing it.)
Also, on my Pentium, the following:
is about twice as fast as Math.pow(x, y) and will return virtually the same result (I think there would be cases where the least significant digit is not as accurate, but that rarely matters).Java Code:public double power(double x, double y) { return Math.exp(y * Math.log(x)); }Neil Coffey
Javamex - Java tutorials and performance info
- 01-16-2009, 07:07 PM #4
Member
- Join Date
- Dec 2008
- Posts
- 8
- Rep Power
- 0
Thanks a lot! That helps me a lot.
Thank you.
- 01-16-2009, 09:13 PM #5
Member
- Join Date
- Sep 2008
- Posts
- 43
- Rep Power
- 0
Similar Threads
-
Computing the sum
By Limuh in forum New To JavaReplies: 3Last Post: 08-13-2008, 06:00 AM -
Rubiks Cube Solver
By sufs2000 in forum Advanced JavaReplies: 0Last Post: 06-03-2008, 03:20 PM -
distributed computing in java
By pushpik in forum Advanced JavaReplies: 0Last Post: 03-31-2008, 06:50 PM -
Computing Fibonacci numbers recursively
By Java Tip in forum Java TipReplies: 0Last Post: 01-22-2008, 08:20 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks