我想对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常量被截断了吗?节目中是否可以打印更多字符串?

最佳答案

piFloating类的方法:

class Fractional a => Floating a where
  pi :: a
  ...

因此pi是多态的,由实例的实现者来适本地定义它。

最常见的实例是FloatDouble,它们的精度有限:
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/

10-12 18:06
查看更多