3

F# 中是否有一种数据类型可以让我计算浮点数到任意/大量小数位?类似于 BigInt 的浮点等价物。

我想做类似的事情

 myLargeFloat = 1.0/7.0
 printfn "%12.500f" myLargeFloat // get the recurring cycle "0.142857142857142857...<500 digits long>"

我使用 BigInt 通过将分子与 bigint 相乘来获得精度。

 myLargeFloat = (bigint.Pow(10I,500)/7I)

有没有更好的方法来做到这一点?

4

3 回答 3

3

F# Powerpack 中的 BigRational 定义如下:

   [<CustomEquality; CustomComparison>]
   [<StructuredFormatDisplay("{StructuredDisplayString}N")>]
   type BigRational =
       | Z of BigInteger
       | Q of BigRationalLarge

其中 aBigRationalLarge定义为:

[<CustomEquality; CustomComparison>]
type BigRationalLarge = 
    | Q of BigInteger * BigInteger

BigInt要以 1000 精度打印 a ,请执行以下操作:

let factorial n = Seq.fold ( * ) 1I [1I .. n]

printf "Factorial of 1000 is %A" (factorial 1000I) 

取自这里

看看这里BigRationalLarge的类型:

有多种方法可以将其转换为不同的打印类型:

   static member ToDouble(n:BigRational) = 
        match n with
        | Z z -> ToDoubleI z
        | Q q -> BigRationalLarge.ToDouble q

    static member ToBigInt(n:BigRational) = 
        match n with 
        | Z z -> z
        | Q q -> BigRationalLarge.integer q 

    static member ToInt32(n:BigRational) = 
        match n with 
        | Z z -> ToInt32I(z)
        | Q q -> ToInt32I(BigRationalLarge.integer q )

转换为 double 如下所示:

   static member ToDouble (Q(p,q)) = 
        ToDoubleI p / ToDoubleI q

将其打印为分子和分母组合的默认方式:

   override n.ToString() =
        let (Q(p,q)) = n 
        if q.IsOne then p.ToString() 
        else p.ToString() + "/" + q.ToString()

这些都不能真正帮助我们获得更高的精度。在指定要打印的小数位数时无法打印它。

所以回答你的问题:

您可以使用 a 的两个BigInt部分创建一个打印您想要的值的函数,BigRational或者您可以编写一个全新的类型来为您执行此操作,但现在还没有类似的东西。

于 2013-03-17T19:13:41.097 回答
2

F# PowerPack中有一个 BigRational 类型。另请参阅http://tomasp.net/blog/powerpack-numeric.aspx

于 2013-03-17T11:25:57.583 回答
1

If you truly require arbitrary-precision floats, you'll have to use @mydogisbox's method. If you just need something with better precision than float (i.e., System.Double) you can try using the decimal type; it's an alias for System.Decimal, which is the .NET implementation of 128-bit binary-coded decimal (BCD). It's much more precise than float but much slower too (like 10-20x).

于 2013-04-30T19:08:54.763 回答