Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Math.Pow (and so on) actually works

So I was googling for a long time and i found almost nothing. I found some info about possible implementation of Math.Pow from this url, but they are inaccurate, for example this code

public static double PowerA(double a, double b)
{
    int tmp = (int)(BitConverter.DoubleToInt64Bits(a) >> 32);
    int tmp2 = (int)(b * (tmp - 1072632447) + 1072632447);
    return BitConverter.Int64BitsToDouble(((long)tmp2) << 32);
}
static void Main(string[] args)
{
    double x = 12.53, y = 16.45;
    Console.WriteLine(Math.Pow(x, y));
    Console.WriteLine(PowerA(x, y));
}

provides output:

1,15158266266297E+18
8,9966384455562E+17

So inaccurate...

I was thinking that it works like a sum of series but I don't know for certain.

like image 973
Alex Zhukovskiy Avatar asked Mar 23 '23 07:03

Alex Zhukovskiy


1 Answers

pow is usually evaluated by this formula:

x^y = exp2(y*log2(x))

Functions exp2(x),log2(x) are directly implemented in FPU. If you want to implement bignums then they can also be evaluated by basic operators with use of precomputed table of sqrt-powers like:

2^1/2, 2^1/4, 2^1/8, 2^1/16, 2^1/32 ...

to speed up the process

In case you need to handle also rooting for negative bases see this:

  • real domain pow based on complex domain math
like image 192
Spektre Avatar answered Apr 01 '23 14:04

Spektre