/* now we have integer ** positive integer. foo & (foo - 1) is zero only for a power of 2. */ if (!(baseuv & (baseuv - 1))) { /* We are raising power-of-2 to postive integer. The logic here will work for any base (even non-integer bases) but it can be less accurate than pow (base,power) or exp (power * log (base)) when the intermediate values start to spill out of the mantissa. With powers of 2 we know this can't happen. And powers of 2 are the favourite thing for perl programmers to notice ** not doing what they mean. */ NV result = 1.0; NV base = baseuok ? baseuv : -(NV)baseuv; int n = 0; /* The logic is this. x ** n === x ** m1 * x ** m2 where n = m1 + m2 so as 42 is 32 + 8 + 2 x ** 42 can be written as x ** 32 * x ** 8 * x ** 2 I can calculate x ** 2, x ** 4, x ** 8 etc trivially: x ** 2n is x ** n * x ** n So I loop round, squaring x each time (x, x ** 2, x ** 4, x ** 8) and multiply the result by the x-value whenever that bit is set in the power. To finish as soon as possible I zero bits in the power when I've done them, so that power becomes zero when I clear the last bit (no more to do), and the loop terminates. */