Mit*_*ops 5 haskell digits show
我想要take更多的Prelude pi值数字.
Prelude> take 4 $ show pi
"3.14"
Run Code Online (Sandbox Code Playgroud)
但
Prelude> take 17 $ show pi
"3.141592653589793"
Prelude> take 170 $ show pi
"3.141592653589793"
Run Code Online (Sandbox Code Playgroud)
是pi不变只是存储在该截断?show中是否有选项可以打印更多数字?
Cla*_*ude 12
pi是一个Floating类的方法:
class Fractional a => Floating a where
pi :: a
...
Run Code Online (Sandbox Code Playgroud)
因此pi是多态的,并且由实例的实现者来适当地定义它.
最常见的情况是Float,并Double具有精度的限制:
Prelude> pi :: Float
3.1415927
Prelude> pi :: Double
3.141592653589793
Run Code Online (Sandbox Code Playgroud)
但没有什么能阻止你使用其他软件包,比如long-double在某些系统上提供更多的内容:
Numeric.LongDouble> pi :: LongDouble
3.1415926535897932385
Run Code Online (Sandbox Code Playgroud)
或者rounded通过MPFR软件实现提供任意多位精度:
Numeric.Rounded> pi :: Rounded TowardNearest 100
3.1415926535897932384626433832793
Numeric.Rounded> pi :: Rounded TowardNearest 500
3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081283
Run Code Online (Sandbox Code Playgroud)
该numbers软件包提供了建设性(精确)实数的纯Haskell实现,可以根据需要显示为多个数字:
Data.Number.CReal> showCReal 100 pi
"3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068"
Run Code Online (Sandbox Code Playgroud)
您也可以使用half软件包具有较低的精度,可以与GPU互操作:
Numeric.Half> pi :: Half
3.140625
Run Code Online (Sandbox Code Playgroud)
当您在pi不给出特定类型的情况下进行评估时,解释器的默认规则就会发挥作用.
每个默认变量都由默认列表中的第一个类型替换,该类型是所有模糊变量类的实例.......如果模块中没有给出默认声明,则假定为:
default (Integer, Double)- https://www.haskell.org/onlinereport/haskell2010/haskellch4.html#x10-790004.3.4
Prelude> :t pi
pi :: Floating a => a
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
(注意:我编写了long-double包,并且是当前的维护者rounded.)