Haskell程式計算給定數字的平方根
Haskell中有多種計算數字平方根的技術。數字的平方根是一個值,當它自身相乘時等於原始數字。例如,9的平方根是3,因為3 x 3 = 9。
演算法
步驟1 - 定義平方根函式
步驟2 - 程式執行將從main函式開始。main()函式控制整個程式。它被寫成main = do。它接受一個整數,需要計算其平方根。
步驟3 - 變數名為“num”,正在初始化。它將儲存一個整數,需要計算其平方根。
步驟4 - 使用'show'函式和'putStrLn'語句在呼叫squareRoot函式時將結果平方根列印到控制檯。
示例1
在此示例中,使用sqrt函式計算數字的平方根並將結果儲存在result變數中。最後,它將計算出的平方根列印到控制檯。
squareRoot :: Double -> Double
squareRoot x = sqrt x
main :: IO()
main = do
let num = 144
let result = squareRoot num
putStrLn ("The square root of " ++ show num ++ " is " ++ show result)
輸出
The square root of 144.0 is 12.0
示例2
在此示例中,使用**運算子將數字提升到0.5的冪,這將得到數字的平方根並將結果儲存在result變數中。最後,它打印出計算出的平方根。
squareRoot :: Double -> Double
squareRoot x = x ** 0.5
main :: IO()
main = do
let num = 169
let result = squareRoot num
putStrLn ("The square root of " ++ show num ++ " is " ++ show result)
輸出
The square root of 169.0 is 13.0
示例3
在此示例中,使用牛頓-拉夫森方法查詢數字的平方根。牛頓-拉夫森方法需要一個函式、它的導數、一個初始猜測和一個容差值。在本例中,函式為y*y - x,其導數為2*y,初始猜測為1。它將迭代,直到猜測的平方與輸入數字之間的差小於容差值(eps)。
squareRoot :: Double -> Double
squareRoot x = newtonRaphson x (\y -> y*y - x) (\y -> 2*y) 1
newtonRaphson :: Double -> (Double -> Double) -> (Double -> Double) -> Double -> Double
newtonRaphson x f f' guess = if abs (f guess) < eps then guess else newtonRaphson x f f' (guess - f guess / f' guess)
where eps = 0.00001
main :: IO()
main = do
let num = 169
let result = squareRoot num
putStrLn ("The square root of " ++ show num ++ " is " ++ show result)
輸出
The square root of 169.0 is 13.000000070110696
結論
Haskell中數字的平方根可以透過使用sqrt函式、使用**運算子或使用牛頓-拉夫森方法來計算。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP