# x power y?

• 04-24-2003
Luigi
x power y?
I made the following function to calculate x power y..
I'd like to upgrade it to make it possible to calculate even if y is decimal.. ex 2^3.456

is that possible?
Im not asking for full code just ideas..

Code:

```double power(double pow, double from)        // x power y {       double temp =  from;       if(pow > 0)       {           --pow;                                // x power 1 means x 1 time not 2 times !           for(int i = 0; i < pow; i++)          temp *= from;        // temp = from x times       }       else if(pow < 0)                {           --pow;                                        //  10/10 = 1 so must add 1..           for(int i = 0; i > pow; --i)          temp /= from;        // temp = from divided x times       }       else if (pow == 0) temp = 1;                        // x power 0 == 1       return temp; }```
• 04-24-2003
DougDbug
You could cheat and use pow()
If you include math.h, you can use pow()

double pow(double x, double y);
float pow(float x, float y); [C++ only]
long double pow(long double x, long double y); [C++ only]
double pow(double x, int y); [C++ only]
float pow(float x, int y); [C++ only]
long double pow(long double x, int y); [C++ only]

The function returns x raised to the power y, x^y.
• 04-24-2003
Luigi
that is an option but id like to try to make it myself..
• 04-24-2003
Luigi
I finally decided to use math.h since I really dunno how to calculate it..
ex: 2^2.5=5.656854249

:confused:
• 04-25-2003
Sang-drax
One way to calculate it yourseld is to use logarithms:

ln( x^y ) = y * ln(x)

x^y = e^( y*ln(x) )

In C++:
Code:

```double myPower(double x, double y) {   return exp( y * log(x) ); }```
• 04-25-2003
DougDbug
Thanks Sang-drax
I couldn't figure it out either. I was thinking that maybe logs were the answer... But, I don't know how to do logs "by hand" either. (Trial & error and interpolation?) So, you still have to use math.h. I know they (the Greeks?) were doing logs long before calculators and computers... Somebody had to figure out where to put the marks on the slide rule!
• 04-25-2003
golfinguy4
Yeah, I think they used a trig table and interpolation. Back then, they did out long calculations by hand. They didn't have tv and had to find something to do I guess.