Haskell 程序计算给定数字的平方根
haskellserver side programmingprogramming更新于 2025/5/2 17:22:17
Haskell 中有多种计算数字平方根的方法。数字的平方根是一个值,当它与自身相乘时,等于原始数字。例如,9 的平方根是 3,因为 3 x 3 = 9。
算法
步骤 1 - 定义平方根函数
步骤 2 - 程序执行将从主函数开始。main() 函数完全控制程序。它写为 main = do。它需要一个要计算其平方根的整数。
步骤 3 - 正在初始化名为"num"的变量。它将保存一个要计算平方根的整数。
步骤 4 - 在调用 squareRoot 函数时,使用"show"函数和"putStrLn"语句将结果平方根打印到控制台。
示例 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 次方,从而得出数字的平方根并将结果存储在结果变量中。最后,它打印出计算出的平方根。
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
在此示例中,使用 Newton-Raphson 方法求数字的平方根。Newton-Raphson 方法需要一个函数、其导数、初始猜测值和容差值。在本例中,函数为 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 函数、** 运算符或 Newton-Raphson 方法计算数字的平方根。