pow() function

hi, i have been trying to write the ready-made (cMath) pow function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>
using namespace std;


float pow(float,int);

int main()
{
	cout<<pow(10,-2);
}

float pow(float a, int b)
{
	if(b==0)
	return 1;
	else if(b==1)
	return a;
	else if(b>1)
	return a*pow(a,b-1);
	

if(b==-1)
return 1/a;
if(b<-1)
{
a*=pow(a,b+1);
return 1/a;
}
	
	
}


I just cant figure out how to return 1/a ONCE in the base case instead of getting 1/a on each stack phase. i know what i wrote returns wrong value. if there was a better way to compute the number when powered by negative number please enlight me :)
Thanks
closed account (D80DSL3A)
Just as you multiply by a for the case b>1 on line 19, you should divide by b for the b<1 case.

In any case I think you have over complicated the treatment. For example, you treat the case
b == 1 explicitly, even though one recursive step will take it to the b=0 case, which is handled already. You should need only the one terminating case.

I got this for the function myself. It seems to work:
1
2
3
4
5
6
float myPow( float b, int e )// using b=base and e=exponent = less confusion for me
{
    if( e == 0 ) return 1.0f;// terminates the recursion
    if( e > 0 ) return myPow( b, e-1 )*b;
    if( e < 0 ) return myPow( b, e+1 )/b;
}


EDIT: Note there is no need for the 'else if' because of the return encountered in the 'if' parts of the code. The return prevents the other if's from executing.
Last edited on
Division is slow. so consider handling the negative exponent case like this:
if (e < 0) return myPow(1.0/b, -e);

Even with this change, the code will be slow for large exponents. You can speed it way up by noticing that b27 = b16 * b8 * b2 * b1 and 27 = 16+8+2+1;
aha i got it now, thanks a lot, cheers !
Topic archived. No new replies allowed.