I was always wondering how I can make a function which calculates the power (e.g. 23) myself. In most languages these are included in the standard library, mostly as pow(double x, double y), but how can I write it myself?
I was thinking about for loops, but it think my brain got in a loop (when I wanted to do a power with a non-integer exponent, like 54.5 or negatives 2-21) and I went crazy 😉
So, how can I write a function which calculates the power of a real number? Thanks
Oh, maybe important to note: I cannot use functions which use powers (e.g. exp), which would make this ultimately useless.
Negative powers are not a problem, they’re just the inverse (
1/x) of the positive power.Floating point powers are just a little bit more complicated; as you know a fractional power is equivalent to a root (e.g.
x^(1/2) == sqrt(x)) and you also know that multiplying powers with the same base is equivalent to add their exponents.With all the above, you can:
Example: