我想对Prelude take
值的更多位数进行pi
。
Prelude> take 4 $ show pi
"3.14"
但
Prelude> take 17 $ show pi
"3.141592653589793"
Prelude> take 170 $ show pi
"3.141592653589793"
刚存储的
pi
常量被截断了吗?节目中是否可以打印更多字符串? 最佳答案
pi
是Floating
类的方法:
class Fractional a => Floating a where
pi :: a
...
因此
pi
是多态的,由实例的实现者来适本地定义它。最常见的实例是
Float
和Double
,它们的精度有限:Prelude> pi :: Float
3.1415927
Prelude> pi :: Double
3.141592653589793
但是没有什么阻止您使用其他软件包,例如
long-double
在某些系统上提供了更多信息:Numeric.LongDouble> pi :: LongDouble
3.1415926535897932385
或
rounded
通过MPFR软件实现任意提供许多精度:Numeric.Rounded> pi :: Rounded TowardNearest 100
3.1415926535897932384626433832793
Numeric.Rounded> pi :: Rounded TowardNearest 500
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081283
numbers
包提供了构造性(精确)实数的纯Haskell实现,可以将其显示为所需的任意位数:Data.Number.CReal> showCReal 100 pi
"3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068"
您还可以使用
half
包来降低精度,也许可以与GPU互操作:Numeric.Half> pi :: Half
3.140625
当您在不指定特定类型的情况下评估
pi
时,解释器的默认规则将发挥作用。Prelude> :t pi
pi :: Floating a => a
Integer
不是Floating
,但是Double
是,因此默认情况下将Double
解析为歧义类型。您可以通过启用-Wtype-defaults
获得更多信息:Prelude> :set -Wtype-defaults
Prelude> pi
<interactive>:2:1: warning: [-Wtype-defaults]
• Defaulting the following constraints to type ‘Double’
(Show a0) arising from a use of ‘print’ at <interactive>:2:1-2
(Floating a0) arising from a use of ‘it’ at <interactive>:2:1-2
• In a stmt of an interactive GHCi command: print it
3.141592653589793
(注意:我编写了
long-double
包,并且是rounded
的当前维护者。)关于haskell - 如何显示haskell的pi的更多数字?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53941896/