Cian Liddy
Cian Liddy

Reputation: 3

This basic programme I wrote for exponents only works with integers - what did I do wrong?

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

Answers (2)

Ervin Szilagyi
Ervin Szilagyi

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):

2^{4.5} = 2^{\frac{9}{2}} =\sqrt[2]{2^{4}}

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 A = x^{b}, where b can be a floating point number and A is the result, we can take the logarithm of both sides:

\log(A) = b \log(x)

Which is equivalent of:

e^{\log(A)} = e^{b\log(x)}

Which simplifies to:

A = e^{b\log(x)}

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:

e^{x} = 1 + x/1! + x^{2}/2! + x^{3}/3!...

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

obiwit
obiwit

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

Related Questions