Reputation: 70406
I want to calculate the result, given any exponent (negative or positive) and a base of type integer. I am using recursion:
public static double hoch(double basis, int exponent) {
if (exponent > 0) {
return (basis * hoch(basis, exponent - 1));
} else if (exponent < 0) {
return ((1 / (basis * hoch(basis, exponent + 1))));
} else {
return 1;
}
}
If exponent is negative 1.0 is returned but that is wrong. For e.g. hoch(2,-2) it should be 0.25. Any ideas what could be wrong?
Upvotes: 1
Views: 22030
Reputation: 21
Working code for raising BASE to a pos or neg BASE:
FUNC Raise_To_Power
LPARAMETERS pnBase, pnPow
DO CASE
CASE pnPow = 0
RETURN 1
CASE pnPow > 0
RETURN pnBase * Raise_To_Power(pnBase, pnPow-1)
CASE pnPow < 0
RETURN 1 / (pnBase * Raise_To_Power(pnBase, -(pnPow+1)))
ENDCASE
ENDFUNC
Upvotes: 0
Reputation: 41749
}else if(exponent < 0){
return ((1/(basis*hoch(basis, exponent+1))))
should be
}else if(exponent < 0){
return (1/hoch(basis, -exponent));
Upvotes: 5
Reputation: 114767
With hoch(2,-2) you actually calculate
1 / (-2 * (1 / (-1 * (1 / 1)))
<=> 1 / (-2 * (1 / (-1))
<=> 1 / (-2 * -1)
<=> 1/2
Upvotes: 1
Reputation: 5490
public static double hoch(double basis, int exponent){
if(exponent > 0){
return basis*hoch(basis, exponent-1);
}else if(exponent < 0){
return hoch(basis, exponent+1)/basis;
}else{
return 1;
}
}
although the more efficient (recursive) solution is
public static double hoch(double basis, int exponent){
if(exponent == 0)
return 1;
else{
double r = hoch(basis, exponent/2);
if(exponent % 2 < 0)
return r * r / basis;
else if(exponent % 2 > 0)
return r * r * basis;
else
return r * r;
}
}
Upvotes: 2
Reputation: 61508
Your parentheses are the wrong way around. You want to be multiplying by the result of the recursive call, not dividing by it; and you want the thing you multiply by to be 1/basis
(which "peels off" one negative exponent).
Upvotes: 1