C# High double precision

前端 未结 6 1479
我在风中等你
我在风中等你 2021-01-19 00:45

I\'m writing a function that calculates the value of PI, and returns it as a double. So far so good. But once the function gets to 14 digits after the decimal place, it can\

6条回答
  •  爱一瞬间的悲伤
    2021-01-19 01:01

    I wouldn't do it in floating point at all.

    Recall that your algorithm is:

    (1 + 1 / (2 * 1 + 1)) *  
    (1 + 2 / (2 * 2 + 1)) *  
    (1 + 3 / (2 * 3 + 1)) *  
    (1 + 4 / (2 * 4 + 1)) *  
    (1 + 5 / (2 * 5 + 1)) *  
    (1 + 6 / (2 * 6 + 1)) *  
    (1 + 7 / (2 * 7 + 1)) *  ...
    

    Every stage along the way you compute a fraction. Why not simply keep that fraction in its numerator / denominator form? The fraction you want to compute is:

    (4 / 3) * 
    (7 / 5) *
    (10 / 7) *
    (13 / 9) * ...
    

    which is just 4 * 7 * 10 * 13 ... on the top and 3 * 5 * 7 * 9 on the bottom.

    Get yourself a BigInteger class (one ships with the 4.0 framework in System.Numerics) and you can easily compute the numerator and denominator as big as you want. Then you just have the problem of converting the quotient to decimal. Well that's easy enough. Presumably you know how to do long division. Just implement a long division algorithm on the numerator and denominator that spits out the desired number of digits.

提交回复
热议问题