Haskell Program to calculate the cube root of the given number


This Haskell article will help us in calculating the cube root of the given number. The cube root of a number is a value that, when multiplied by itself three times, equals the original number. For example, the cube root of 8 is 2 because 2 x 2 x 2 = 8.

In mathematics, cube root of a number x is represented as ∛x.

Algorithm

  • Step 1 − Define a user-defined function and name it as cubeRoot

  • 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 cube root is to be calculated. Then it will test the cubeRoot function by passing a number and printing the result.

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

  • Step 4 − The resultant cube root is printed to the console using ‘print’ function on calling the cubeRoot function.

Example 1

In this example, the cubeRoot function takes a double (a decimal number) as an argument and returns its cube root.

import Data.Fixed

cubeRoot :: Double -> Double
cubeRoot x = (cuberoot x) / 1
   where cuberoot = (** (1/3))

main :: IO ()
main = do
   let num = 8
   print (cubeRoot num)

Output

2.0

Example 2

In this example, the exp function is used to calculate the cube root by taking the natural logarithm of the input number, dividing it by 3, and then taking the exponential.

import Data.Fixed
import Text.Printf
cubeRoot :: Double -> Double
cubeRoot x = exp (log x / 3)

main :: IO ()
main = do
   let num = 8
   printf "Cuberoot of %f is " num
   print (cubeRoot num)

Output

Cuberoot of 8.0 is 2.0

Example 3

In this example, we are going to see that how we can calculate the cube root of the given number using Newton-Raphson Method.

cubeRoot :: Double -> Double
cubeRoot x = cubeRootNewtonRaphson x 1

cubeRootNewtonRaphson :: Double -> Double -> Double
cubeRootNewtonRaphson x guess =
   if abs (guess^3 - x) < 0.00001
   then guess
   else cubeRootNewtonRaphson x (guess - (guess^3 - x) / (3 * guess^2))

main :: IO ()
main = do
   let num = 8
   print (cubeRoot num)

Output

2.0000000000120624

Conclusion

The cube root of a number in Haskell, can be calculated by using the cuberoot function, by using exp function or by using Newton-Raphson method.

Updated on: 01-Mar-2023

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements