How can I write a power function myself?

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:

  • Decompose the exponent in a integer part and a rational part.
  • Calculate the integer power with a loop (you can optimise it decomposing in factors and reusing partial calculations).
  • Calculate the root with any algorithm you like (any iterative approximation like bisection or Newton method could work).
  • Multiply the result.
  • If the exponent was negative, apply the inverse.

Example:

2^(-3.5) = (2^3 * 2^(1/2)))^-1 = 1 / (2*2*2 * sqrt(2))

Leave a Comment