problem with recursive power function

hey guys am having a problem with my power function that calculates power it works properly with exponents that are intergers but crashes with exponents that are double type please help thanx in advance

1
2
3
4
5
6
7
8
9
10
11
12
13
 double power(double base, double exp)
{


    if ( exp == 0 )
        return 1;
    else if ( exp == 1 )
        return base;
    else
        return base * power(base, exp-1);
    double result = base;

}
if ( exp == 0 ) Do not compare floating point values which you get as a computation result for equality directly.

What happens if I pass 0.5 as exponent?

Using recursion to calculate power of arbitrary values is not good. You shpould use more elaborate math in here.
can u help me impliment such a condition in my function am out of ideas.....
From math we know that pow(x, n) = exp(n * log(x))
Now you need to implement exp and log functions. There is many ways to do that (either by using naive approach with Tailor series or doing something smarter), but I will suggest to jusr use tandard functions. If you still want to make your own functions, there is reference log() implementation: http://www.netlib.org/fdlibm/e_log.c


Actually for perfomance math functions are often implemented directly in assembly.
Topic archived. No new replies allowed.