gpt4 book ai didi

f# - F# 中是否有任意精度 float ?像 BigFloat 这样的东西?

转载 作者:行者123 更新时间:2023-12-01 10:55:28 26 4
gpt4 key购买 nike

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

我想做类似的事情

 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)

有更好的方法吗?

最佳答案

BigRational 在 F# Powerpack 中是这样定义的:

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

BigRationalLarge 定义为:

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

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

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

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

取自here .

查看 BigRationalLarge 类型 here :

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

   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()

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

所以回答你的问题:

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

关于f# - F# 中是否有任意精度 float ?像 BigFloat 这样的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15460180/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com