Here is a modified version of pow that accepts both positive and negative powers:
----
real pow(real x, int n)
{
real p = 1.0, v;
if (n < 0)
{
switch (n)
{
case -1:
return 1 / x;
case -2:
return 1 / (x * x);
default:
}
n = -n;
v = p / x;
}
else
{
switch (n)
{
case 0:
return 1.0;
case 1:
return x;
case 2:
return x * x;
default:
}
v = x;
}
while (1)
{
if (n & 1)
p *= v;
n >>= 1;
if (!n)
break;
v *= v;
}
return p;
}
----
Comment #1 by samukha — 2008-04-07T01:42:28Z
Created attachment 242
A pow patch for phobos
Comment #2 by samukha — 2008-04-07T01:49:27Z
Corrected the summary
Comment #3 by andrei — 2008-04-07T14:14:30Z
How about pow called with an unsigned exponent larger than int.max?
Comment #4 by samukha — 2008-04-07T15:40:44Z
Right. My bad.
Comment #5 by caron800 — 2008-04-08T02:14:40Z
On 07/04/2008, [email protected] <[email protected]> wrote:
> How about pow called with an unsigned exponent larger than int.max?
Overload it for both int and uint, and have the int version accept
negative values?