Search code examples
cmathpow

A numbers power between 0 and 1 in C


I'm making a program to replace math.h's pow() function. I'm not using any functions from math.h.

The problem is, I can calculate powers as integers like

  • 15-2

  • 45.3211

but I can't calculate

  • x2.132

My program first finds integer power of x (x2) and multiplies it by (x0.132).

I know that x0.132 is 1000th root of x to the power 132 but I can't solve it.

How can I find xy (0 < y < 1)


Solution

  • To compute x ^ y, 0 < y < 1 :

    1. Approximate y as a rational fraction, (a/b)

    (Easiest way: Pick whatever b you want to get sufficient accuracy as a constant.
    Then use: a = b * y.)

    1. Approximate the b root of y using any method you like, such as Newton's.

    (Simplest way: You know it's between 0 and b and can easily tell if a given value is too low or too high. So keep a min that starts at zero and a max that starts at b. Repeatedly try (min + max) / 2, see if it's too big or too small, and adjust min or max appropriately. Repeat until min and max are nearly the same.)

    1. Raise that to the a power.

    (Possibly by repeatedly multiplying it by itself. Optimize this if you like. For example, a^4 can be computed with just two multiplications, one to find a^2 and then one to square it. This generalizes easily.)