How does one carry out exponentiation in java without using the math class. If you can help, please provide an example to help pick up the concept. Thanks for all your input.

Printable View

- 10-13-2009, 08:21 PMBlueJ CoderPerforming Exponentiation in Java without the Math Class
How does one carry out exponentiation in java without using the math class. If you can help, please provide an example to help pick up the concept. Thanks for all your input.

- 10-13-2009, 08:51 PMr035198x
Forget about doing it in Java for a moment.

How would you do it on paper? Only move to the compiler if you get your algorithm right. - 10-14-2009, 12:06 AMxcallmejudasx
you can use a loop but that's horribly inefficient. I can post you the algorithm once I find my notes from college on exponents. I think it's called like the medieval peasant addition formula or something if you want to look around.

- 10-14-2009, 12:17 AMJnoobs
in my college class, if u had 2^3 u would write

Code:`total = 2 * 2 * 2;`

- 10-14-2009, 05:22 PMxcallmejudasx
Break it down into smaller chunks and use a recursive formula to calculate it. take for example 2^24 which is (2(2^23) which is (2(2(2^22) which is (2(2(2(2^21) etc.

You end up with x^n = x(x^n-1) = x(x(x^n-2)) etc. I believe you can approximate this using a limit. lim i -> n of x^i(x^n-i) would be your general equation. from there you recursively calculate your answer. (x is your base number, n is your max exponent, i is an iterator)

After actually writing all this out I'm not sure how much faster it's going to be since you're still doing an exponential. Someone want to improve what I wrote? Or just say if I went the completely wrong direction and tell the OP to ignore everything I've just typed. - 10-14-2009, 06:03 PMArnold
I've checked out the source code of the Math class recently and I found out that it delegates all these operations to another class called the StrictMath class.

When I checked that out it appeared that all these methods are 'natives', which probably means that it is done in the processor or something.

So I still don't know what kind of algorithm to use for broken exponents. It's one of the greatests mysteries in math to me. - 10-14-2009, 06:10 PMxcallmejudasx
I know that multiplication by 2's can be done using simple hardware switches. Say for calculating 2^32 the compiler wouldn't actually calculate it the same way it would say 5^13. It would drop down and do byte level arithmetic and just shift the bits over(I think that's how you multiply by 2 with bits)

- 10-14-2009, 07:07 PMFubarable
Pardon my ignorance, but what is a "broken" exponent? Thanks in advance!

- 10-14-2009, 08:13 PMArnold
- 10-14-2009, 09:48 PMFubarable
Ah, gotcha. This would require logarithms or something similar to solve, I'd guess.