Haskell Program to calculate the square root of the given number


There are different techniques in Haskell to calculate a square root of a number. The square root of a number is a value that, when multiplied by itself, equals the original number. For example, the square root of 9 is 3 because 3 x 3 = 9.

Algorithm

  • Step 1 − Defined the square root function

  • Step 2 − Program execution will be started from main function. The main() function has whole control of the program. It is written as main = do. It takes an integer whose square root is to be calculated.

  • Step 3 − The variable named, “num” is being initialized. It will hold an integer whose square root is to be calculated.

  • Step 4 − The resultant square root is printed to the console using ‘show’ function and ‘putStrLn’ statement on calling the squareRoot function.

Example 1

In this example, the sqrt function is used to calculate the square root of the number and stores the result in the result variable. Finally, it prints the calculated square root to the console.

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)

Output

The square root of 144.0 is 12.0

Example 2

In this example, the ** operator is used to raise the number to the power of 0.5, which gives the square root of the number and stores the result in the result variable. Finally, it prints out the calculated square root.

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)

Output

The square root of 169.0 is 13.0

Example 3

In this example, the Newton-Raphson method is used to find the square root of the number. The Newton-Raphson method requires a function, its derivative, an initial guess and a tolerance value. In this case, the function is y*y - x, its derivative is 2*y and the initial guess is 1. It will iterate until the difference between the square of the guess and the input number is less than the tolerance value(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)

Output

The square root of 169.0 is 13.000000070110696

Conclusion

The square root of a number in Haskell, can be calculated by using the sqrt function, by using ** operator or by using Newton-Raphson method.

Updated on: 01-Mar-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements