Reputation: 3
I am building some basic programs as a way to practice different programming techniques. I thought I had written a programme to calculate exponents but it doesn't work correctly.
It works fine if I input integers ie. squared (2,5) but (2,4.5) doesn't work.
public static double squared(double a, double b) {
double a1 = a;
double sq = 0;
while (b > 1) {
sq = a*a1;
a =sq;
b--;
}
return sq;
}
public static void main(String[] args) {
System.out.println(squared(2,2));
}
Upvotes: 0
Views: 59
Reputation: 16775
Your algorithm works for integer numbers, but in order to calculate the power with a floating point exponent, your approach wont work.
First, let's clear what a float exponent means by taking your example of pow(2, 4.5)
:
So in order to calculate this, first we have to transform the floating point number to a fraction and then calculate the power and square root. This doable, but it's very tedious and they are far more better solution to do this.
If we have , where b
can be a floating point number and A
is the result, we can take the logarithm of both sides:
Which is equivalent of:
Which simplifies to:
Now this can be done in Java very easily:
public static void main(String args[]) {
double a = 2;
double b = 4.5;
double A = Math.exp(b * Math.log(a));
System.out.println(A);
}
If you don't want to use the built-in exp
function, we can use the Newton-Raphson formula to calculate it:
where: !
denotes the factorial of a number.
Your initial algorithm can be used to compute the pow
of an x
with integer exponent.
Upvotes: 2
Reputation: 100
Your program works as expect if b
is an integer, because your code assumes b
is an integer.
The same result will be computed whether b
is 4 ou 4.5, because both 0 and 0.5 are smaller than 1 (thus ending the loop).
Upvotes: 2