開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- Haskell (プログラミング言語)
- Haskell Platform(ghci)(処理系)
関数プログラミング入門(Richard Bird (著)、山下伸夫 (翻訳)、オーム社)の第3章(数値)、3.6(例: 線形探索と二分探索)、練習問題3.6.1、3.6.2、3.6.3、3.6.4を取り組んでみる。
練習問題3.6.1、3.6.2、3.6.3、3.6.4
コード(Emacs)
-- 3.6.3
eps :: Double
eps = 0.00001
sqrt :: Double -> Double
sqrt x = until done improve x
where done y = abs (y * y - x) < eps * x
improve y = (y + x / y) / 2
-- 3.6.4
sqrt' x = until done improve x
where done y = abs (y - y') < eps * abs y
where y' = improve y
improve y = (y + x / y) / 2
a, b :: Double
a = 2
b = 12345
main :: IO ()
main = do
print (Main.sqrt a)
print (sqrt' a)
print (Main.sqrt b)
print (sqrt' b)
入出力結果(Terminal, ghci, runghc)
$ runghc sample6.hs 1.4142156862745097 1.4142156862745097 111.10805770848404 111.10805770848404 $
0 コメント:
コメントを投稿