转换为double和back的BigInteger / BigRational问题

时间:2015-03-28 22:44:19

标签: c# biginteger

也许我不明白如何使用这两种类型:BigInteger / BigRational,但一般来说我想实现这个等式:enter image description here

这是我的数据:n = 235,K = 40,这个小p(实际上称为rho)是5.一开始问题出现在Power函数中:结果非常非常大 - 所以这就是我使用BigInteger库的原因。但后来我意识到会有一个分区,结果将是一些双重类型 - 所以我改为BigRational库。

这是我的代码:

static void Main(string[] args)
    {
        var k = 40;
        var n = 235;
        var p = 5;

        // the P(n) equation
        BigRational pnNumerator = BigRational.Pow(p, n);
        BigRational pnDenominator = BigRational.Pow(k, (n - k)) * Factorial(k);


        // the P(0) equation

        //---the right side of "+" sign in Denominator
        BigRational pk = BigRational.Pow(p, k);
        BigRational factorialK = Factorial(k);
        BigRational lastPart = (BigRational.Subtract(1, (double)BigRational.Divide(p, k)));
        BigRational factorialAndLastPart = BigRational.Multiply(factorialK, lastPart);
        BigRational fullRightSide = BigRational.Divide(pk, factorialAndLastPart);
        //---the left side of "+" sign in Denominator
        BigRational series = Series(k, p, n);


        BigRational p0Denominator = series + fullRightSide;
        BigRational p0Result = BigRational.Divide(1, p0Denominator);

        BigRational pNResult = BigRational.Divide((pnNumerator * p0Result), pnDenominator);
        Console.WriteLine(pNResult);
        Console.ReadKey();
    }

    static BigRational Series(int k, int p, int n)
    {
        BigRational series = new BigRational(0.0);
        var fin = k - 1;
        for (int i = 0; i < fin; i++)
        {
            var power = BigRational.Pow(p, i);
            var factorialN = Factorial(n);
            var sum = BigRational.Divide(power, factorialN);
            series += sum;
        }
        return series;
    }

    static BigRational Factorial(int k)
    {
        if (k <= 1)
            return 1;
        else return BigRational.Multiply(k, Factorial(k - 1));
    }

主要问题是它没有返回任何“正常”值,例如0.3或0.03。打印到控制台的结果是一个非常长的数字(如1200位数字)......

有人可以看看我的代码并帮我修复问题,并能够通过代码解决这个方程式。谢谢

1 个答案:

答案 0 :(得分:5)

Console.WriteLine(pNResult);在引擎盖下调用BigRational.ToString(),以numerator/denominator格式打印数字。

考虑到在这种情况下分子和分母的大小,输出中的/很容易错过。

BigRational支持转化为decimaldouble。在这种情况下,结果太小,无法容纳decimal。转换为double,会得到结果7.89682541396914E-177

如果您需要更高的精确度,则需要自定义转换为十进制格式字符串,例如this Stackoverflow answer中的字符串。

使用该自定义转换例程将结果提取到1000小数位 -

Console.WriteLine(pNResult.ToDecimalString(1000));

- 将结果显示为:

  

0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000789682541396913067701288971374594928289711703493803367409352696515396846505250336760031345932833613055306751124705284082191770250442541164627985614504423182900466262484517230403977702636751091071454613107796417050931561063111437276082086294733595664574613844746331128503359500172095581365751358013886686875712844922410305610196069559862655856366603048897920278944601042161767197176715008433996856861464329823584412255783660590015766823885032272372020778813346953523386383833377171033031535211088127506442605623511868665876294562925069712525251259767555402740416517401941084305557516487079335926434104752149243942236401688573409535631110979793944413031007010081200081663393650897715850378802353256731431528145105865363353806713608652304288570496583682425436532345998174301858796484274342163783565180367764771701302276283 07039


要检查您的计算代码是否正常运行,您可以为不同的函数添加单元测试(FactorialSeries以及P本身的计算。)

这里实用的方法是手动计算knp的某些小值的结果,并检查您的函数是否计算出相同的结果。

如果您正在使用Visual Studio,则可以使用this MSDN page作为创建单元测试项目的起点。请注意,测试中的功能必须对单元测试项目可见,并且您的单元测试项目需要将一个引用添加到您正在进行计算的现有项目中,如链接中所述。 / p>

Factorial开始,这是最容易检查的,您可以添加如下测试:

[TestClass]
public class UnitTestComputation
{
    [TestMethod]
    public void TestFactorial()
    {
        Assert.AreEqual(1, Program.Factorial(0));
        Assert.AreEqual(1, Program.Factorial(1));
        Assert.AreEqual(2, Program.Factorial(2));
        Assert.AreEqual(6, Program.Factorial(3));
        Assert.AreEqual(24, Program.Factorial(4));
    }
}

您问题中的代码通过了该测试。

然后,您可以为Series功能添加测试方法:

[TestMethod]
public void TestSeries()
{
    int k = 1;
    int p = 1;
    BigRational expected = 1;
    Assert.AreEqual(expected, Program.Series(k, p));

    k = 2;
    p = 1;
    expected += 1;
    Assert.AreEqual(expected, Program.Series(k, p));

    k = 3;
    p = 1;
    expected += (BigRational)1 / (BigRational)2;
    Assert.AreEqual(expected, Program.Series(k, p));

    k = 1;
    p = 2;
    expected = 1;
    Assert.AreEqual(expected, Program.Series(k, p));

    k = 2;
    p = 2;
    expected += 2;
    Assert.AreEqual(expected, Program.Series(k, p));
}

这在您的代码中出现了一些问题:

  • n实际上不应该是此函数的参数,因为在此上下文中n不是函数P的参数,但实际上只是& #34;指数的求和&#34 ;. n此功能的本地值由您的i变量表示。
  • 这表示您的Factorial(n)来电需要更改为Factorial(i)
  • 循环也是一个接一个,因为求和的Sigma表示法包含Sigma顶部的数字,所以你应该有<= fin(或者你也可以写这个如< k)。

这是更新后的Series功能:

// CHANGED: Removed n as parameter (n just the index of summation here)
public static BigRational Series(int k, int p)
{
    BigRational series = new BigRational(0.0);
    var fin = k - 1;
    // CHANGED: Should be <= fin (i.e. <= k-1, or < k) because it's inclusive counting
    for (int i = 0; i <= fin; i++)
    {
        var power = BigRational.Pow(p, i);
        // CHANGED: was Factorial(n), should be factorial of n value in this part of the sequence being summed.
        var factorialN = Factorial(i);
        var sum = BigRational.Divide(power, factorialN);
        series += sum;
    }
    return series;
}

要测试P(n)计算,您可以将其移到自己的函数中进行测试(我在这里称之为ComputeP):

[TestMethod]
public void TestP()
{
    int n = 1;
    int k = 2;
    int p = 1;
    // P(0) = 1 / (2 + 1/(2*(1 - 1/2))) = 1/3
    // P(1) = (1/(1/2 * 2)) * P(0) = P(0) = 1/3 
    BigRational expected = 1;
    expected /= 3;
    Assert.AreEqual(expected, Program.ComputeP(k, n, p));

    n = 2;
    k = 2;
    p = 1;
    // P(2) = (1/(1*2)) * P(0) = 1/6
    expected = 1;
    expected /= 6;
    Assert.AreEqual(expected, Program.ComputeP(k, n, p));
}

这显示了计算P(n)时出现的问题 - 你在double有一个不应该存在的演员(结果是不准确的) - 你需要保留所有中间结果为BigRational)。没有必要进行演员表,所以只需删除它就可以解决这个问题。

以下是更新的ComputeP功能:

public static BigRational ComputeP(int k, int n, int p)
{
    // the P(n) equation
    BigRational pnNumerator = BigRational.Pow(p, n);
    BigRational pnDenominator = BigRational.Pow(k, (n - k)) * Factorial(k);


    // the P(0) equation

    //---the right side of "+" sign in Denominator
    BigRational pk = BigRational.Pow(p, k);
    BigRational factorialK = Factorial(k);
    // CHANGED: Don't cast to double here (loses precision)
    BigRational lastPart = (BigRational.Subtract(1, BigRational.Divide(p, k)));
    BigRational factorialAndLastPart = BigRational.Multiply(factorialK, lastPart);
    BigRational fullRightSide = BigRational.Divide(pk, factorialAndLastPart);
    //---the left side of "+" sign in Denominator
    BigRational series = Series(k, p);


    BigRational p0Denominator = series + fullRightSide;
    BigRational p0Result = BigRational.Divide(1, p0Denominator);

    BigRational pNResult = BigRational.Divide((pnNumerator * p0Result), pnDenominator);
    return pNResult;
}

为避免混淆,这里是整个更新的计算程序:

using System;
using System.Numerics;
using System.Text;
using Numerics;

public class Program
{
    public static BigRational ComputeP(int k, int n, int p)
    {
        // the P(n) equation
        BigRational pnNumerator = BigRational.Pow(p, n);
        BigRational pnDenominator = BigRational.Pow(k, (n - k)) * Factorial(k);


        // the P(0) equation

        //---the right side of "+" sign in Denominator
        BigRational pk = BigRational.Pow(p, k);
        BigRational factorialK = Factorial(k);
        // CHANGED: Don't cast to double here (loses precision)
        BigRational lastPart = (BigRational.Subtract(1, BigRational.Divide(p, k)));
        BigRational factorialAndLastPart = BigRational.Multiply(factorialK, lastPart);
        BigRational fullRightSide = BigRational.Divide(pk, factorialAndLastPart);
        //---the left side of "+" sign in Denominator
        BigRational series = Series(k, p);


        BigRational p0Denominator = series + fullRightSide;
        BigRational p0Result = BigRational.Divide(1, p0Denominator);

        BigRational pNResult = BigRational.Divide((pnNumerator * p0Result), pnDenominator);
        return pNResult;
    }

    // CHANGED: Removed n as parameter (n just the index of summation here)
    public static BigRational Series(int k, int p)
    {
        BigRational series = new BigRational(0.0);
        var fin = k - 1;
        // CHANGED: Should be <= fin (i.e. <= k-1, or < k) because it's inclusive counting
        for (int i = 0; i <= fin; i++)
        {
            var power = BigRational.Pow(p, i);
            // CHANGED: was Factorial(n), should be factorial of n value in this part of the sequence being summed.
            var factorialN = Factorial(i);
            var sum = BigRational.Divide(power, factorialN);
            series += sum;
        }
        return series;
    }

    public static BigRational Factorial(int k)
    {
        if (k <= 1)
            return 1;
        else return BigRational.Multiply(k, Factorial(k - 1));
    }

    static void Main(string[] args)
    {
        var k = 40;
        var n = 235;
        var p = 5;
        var result = ComputeP(k, n, p);
        Console.WriteLine(result.ToDecimalString(1000));
        Console.ReadKey();
    }
}

// From https://stackoverflow.com/a/10359412/4486839
public static class BigRationalExtensions
{
    public static string ToDecimalString(this BigRational r, int precision)
    {
        var fraction = r.GetFractionPart();

        // Case where the rational number is a whole number
        if (fraction.Numerator == 0 && fraction.Denominator == 1)
        {
            return r.GetWholePart() + ".0";
        }

        var adjustedNumerator = (fraction.Numerator
                                           * BigInteger.Pow(10, precision));
        var decimalPlaces = adjustedNumerator / fraction.Denominator;

        // Case where precision wasn't large enough.
        if (decimalPlaces == 0)
        {
            return "0.0";
        }

        // Give it the capacity for around what we should need for 
        // the whole part and total precision
        // (this is kinda sloppy, but does the trick)
        var sb = new StringBuilder(precision + r.ToString().Length);

        bool noMoreTrailingZeros = false;
        for (int i = precision; i > 0; i--)
        {
            if (!noMoreTrailingZeros)
            {
                if ((decimalPlaces % 10) == 0)
                {
                    decimalPlaces = decimalPlaces / 10;
                    continue;
                }

                noMoreTrailingZeros = true;
            }

            // Add the right most decimal to the string
            sb.Insert(0, decimalPlaces % 10);
            decimalPlaces = decimalPlaces / 10;
        }

        // Insert the whole part and decimal
        sb.Insert(0, ".");
        sb.Insert(0, r.GetWholePart());

        return sb.ToString();
    }
}

这是整个单元测试程序:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Numerics;


[TestClass]
public class UnitTestComputation
{
    [TestMethod]
    public void TestFactorial()
    {
        Assert.AreEqual(1, Program.Factorial(0));
        Assert.AreEqual(1, Program.Factorial(1));
        Assert.AreEqual(2, Program.Factorial(2));
        Assert.AreEqual(6, Program.Factorial(3));
        Assert.AreEqual(24, Program.Factorial(4));
    }

    [TestMethod]
    public void TestSeries()
    {
        int k = 1;
        int p = 1;
        BigRational expected = 1;
        Assert.AreEqual(expected, Program.Series(k, p));

        k = 2;
        p = 1;
        expected += 1;
        Assert.AreEqual(expected, Program.Series(k, p));

        k = 3;
        p = 1;
        expected += (BigRational)1 / (BigRational)2;
        Assert.AreEqual(expected, Program.Series(k, p));

        k = 1;
        p = 2;
        expected = 1;
        Assert.AreEqual(expected, Program.Series(k, p));

        k = 2;
        p = 2;
        expected += 2;
        Assert.AreEqual(expected, Program.Series(k, p));
    }

    [TestMethod]
    public void TestP()
    {
        int n = 1;
        int k = 2;
        int p = 1;
        // P(0) = 1 / (2 + 1/(2*(1 - 1/2))) = 1/3
        // P(1) = (1/(1/2 * 2)) * P(0) = P(0) = 1/3 
        BigRational expected = 1;
        expected /= 3;
        Assert.AreEqual(expected, Program.ComputeP(k, n, p));

        n = 2;
        k = 2;
        p = 1;
        // P(2) = (1/(1*2)) * P(0) = 1/6
        expected = 1;
        expected /= 6;
        Assert.AreEqual(expected, Program.ComputeP(k, n, p));
    }
}

顺便提一下,P(n)结果显示npk输入值的更新程序:

  

0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000059310998076906691602597256939842426766980762972620001737529086159089826990227786993836596996132096947335600166690648000711911483092183991362359112419204795509131895183190255040416733605468369707165476507151902006043712939894503552195473846378622102942758939768884724611281053695819436403969338717059242552713624395241670452606973681158738068887609192625590836127557524949284597090367649242968492977940260003248101888687569897253353489084179603462633767484662046204629453748858090112933862562834947435894696206522789059974477556263778455365648864984114859153355789641898804445791499985424103897447857657890962676582356581775879268248000961961343886736591269799652795777524835098780143014177687517180838227296042647695374252876962655564295709302855399390835622600757040400559117445121684647171016276 0343


注意:您应该在单元测试中添加更多您已经手工检查过的结果,并检查我在这里工作的任何代码,将代数解释为代码以确保这是正确的。