如何获得的BigInteger的双战俘在C#中? [英] how to get the BigInteger to the pow Double in C#?

查看:137
本文介绍了如何获得的BigInteger的双战俘在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 BigInteger.Pow 方法来计算像10 ^ 12345.987654321这样的方法,但是这个方法只接受整数作为指数,如下所示:

I tried to use BigInteger.Pow method to calculate something like 10^12345.987654321 but this method only accept integer number as exponent like this:


BigInteger.Pow(BigInteger x,int y)

BigInteger.Pow(BigInteger x, int y)

可以在上面的方法中使用双数作为指数?

so how can I use double number as exponent in above method?

推荐答案

C#中没有任何精度大数字支持,直接完成。有一些替代方法(例如寻找第三方库),或者你可以尝试类似下面的代码 - 如果基数足够小,像你的情况。

There's no arbitrary precision large number support in C#, so this cannot be done directly. There are some alternatives (such as looking for a 3rd party library), or you can try something like the code below - if the base is small enough, like in your case.

public class StackOverflow_11179289
{
    public static void Test()
    {
        int @base = 10;
        double exp = 12345.123;
        int intExp = (int)Math.Floor(exp);
        double fracExp = exp - intExp;
        BigInteger temp = BigInteger.Pow(@base, intExp);
        double temp2 = Math.Pow(@base, fracExp);
        int fractionBitsForDouble = 52;
        for (int i = 0; i < fractionBitsForDouble; i++)
        {
            temp = BigInteger.Divide(temp, 2);
            temp2 *= 2;
        }

        BigInteger result = BigInteger.Multiply(temp, (BigInteger)temp2);

        Console.WriteLine(result);
    }
}

这个想法是使用大整数数学计算功率的指数的整数部分,然后使用双(64位浮点)数学计算分数部分的功率。然后,使用

The idea is to use big integer math to compute the power of the integer part of the exponent, then use double (64-bit floating point) math to compute the power of the fraction part. Then, using the fact that

a ^ (int + frac) = a ^ int * a ^ frac

我们可以将这两个值组合成一个大的整数。但是简单地将double值转换为BigInteger会失去很多精度,所以我们首先将精度移动到bigInteger上(使用上面的循环,事实上 double type使用52位的精度),然后乘以结果。

we can combine the two values into a single big integer. But simply converting the double value to a BigInteger would lose a lot of its precision, so we first "shift" the precision onto the bigInteger (using the loop above, and the fact that the double type uses 52 bits for the precision), then multiplying the result.

请注意,结果是一个近似,如果你想要一个更精确的数字,需要一个可以进行任意精度浮点运算的库。

Notice that the result is an approximation, if you want a more precise number, you'll need a library that does arbitrary precision floating point math.

更新:如果基数/指数足够小,范围 double ,我们可以简单地做什么Sebastian Piu建议( new BigInteger(Math.Pow((double)@base,exp) / code>)

Update: If the base / exponent are small enough that the power would be in the range of double, we can simply do what Sebastian Piu suggested (new BigInteger(Math.Pow((double)@base, exp)))

这篇关于如何获得的BigInteger的双战俘在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆