How Math.Pow (and so on) actually works

佐手、 提交于 2019-11-26 08:34:24

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/19012100/how-math-pow-and-so-on-actually-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!