Java does not have an exponentiation operator. I want to write a function that c
ID: 3662323 • Letter: J
Question
Java does not have an exponentiation operator. I want to write a function that can raise a double base to an int power. To do this, we will use a recursive function public static double raise(base, exp, level) { Base is the base to raise, exp is the power to raise it to. I will explain level later. To accomplish this, first we deal with the easy stuff. 1) 0.0 raised to a negative power should return Double.Infinity. 2) 0.0 raised to a power that is >= 0 should return 0.0 3) any base raised to the power 1 should return the base. These are the non-recursive exits. 4) if exp < 0 and base != 0, set base = 1.0/base and exp = -exp. At this point, the exponent is positive and we are ready for the recursive case. Observe that if exp is even, base ^ exp is base^(exp/2) * base ^ (exp/2). If exp is odd, base ^ exp is given by base^(exp/2) * base^(exp/2) * base. These observations create the working of the recursive case. For even exp, return raise(base, exp/2) * raise(base, exp/2) For odd exp, return raise(base, exp/2) * raise(base, exp/2) * base. This will work, but is inefficient because each of the above lines of code calls raise twice. We can make it much better by writing: temp = raise(base, exp/2); retval = temp * temp; if (exp % 2) == 1 retval *= temp; return retval; I would like you to figure out how much better this is. To do this, implement the algorithm both ways (with temp, and with 2 calls to raise). Add a static class variable public class MyPow { public static countGbl = 0; and then in either of the raise methods, increment count each time you enter the recursive portion of the code. If you put your main program in the same file, it also can access countGbl directly. Then you can write a main program that repeatedly sets countGbl to 0, then calculates raise(0.0, i) for i = 1, 2, 3, ...,100. In each case, record the value of count, and plot these values against i. (Use excel if you like) You should see rather different shaped curves for the two diffefrent implementations of the algorithm.
Explanation / Answer
I have written two java functionts to achieve the same.
In my opinion recursive will fail for larger values of exponents due to stack overflow issues in machine.
for raise with 2 calls java implementation will be
public static long raise(long base, long exp){
if(exp ==0){
return 1;
}
if(exp ==1){
return base;
}
if(exp % 2 == 0){
return raise(base, exp/2) * raise(base, exp/2);
}else{
return base * raise(base, (exp -1)/2) * raise(base, (exp -1)/2);
}
}
with temp variable it will be
public static long raise(long base, long exp)
{
int temp;
if(exp == 0)
return 1;
temp = raise(base, exp/2);
if (exp%2 == 0)
return temp*temp;
else
return base*temp*temp;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.