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函数、使用**运算符或使用牛顿-拉夫森方法来计算。
广告