Python: Calculate Square Root

1. Introduction

Finding the square root of a number is a common mathematical operation. While Python provides built-in methods to do this, understanding how to calculate it manually can be valuable. In this post, we will explore both the built-in approach and the manual approach to compute the square root of a given number.

2. Program Overview

1. Introduce Python's built-in sqrt function.

2. Introduce the manual method using the Babylonian (or Heron's) method.

3. Accept a number from the user.

4. Calculate the square root using both methods.

5. Display the results to the user.

3. Code Program

# Python program to find the square root of a number

# Using Python's built-in function
import math

def sqrt_builtin(num):
    """Function to compute the square root using Python's built-in method."""
    return math.sqrt(num)

# Using Babylonian (or Heron's) method
import math  # This is the missing part

def sqrt_manual(num):
    """Function to compute the square root using Babylonian method."""
    if num < 0:
        return "Square root of negative number is complex"
    x = num
    y = 1
    # Set a very small tolerance level
    epsilon = 0.000001
    while x - y > epsilon:
        x = (x + y) / 2
        y = num / x
    return x

# Accept input from the user
number = float(input("Enter a number to find its square root: "))

# Calculate the square roots using both built-in method and Babylonian method
root_builtin = math.sqrt(number)  # Here's the correction
root_manual = sqrt_manual(number)

# Display the results
print(f"Square root (using built-in function) of {number} is {root_builtin}")
print(f"Square root (using Babylonian method) of {number} is {root_manual}")

Output:

Enter a number to find its square root: 25
Square root (using built-in function) of 25.0 is 5.0
Square root (using Babylonian method) of 25.0 is 5.000000000053722

4. Step By Step Explanation

1. Python's built-in library math provides a function called sqrt which computes the square root directly.

2. The Babylonian (or Heron's) method is an iterative approach to finding the square root of a number. It works by repeatedly taking the average of an estimate x and num/x until the values converge to the actual square root. The method is initialized with x being the number and y being 1.

3. The loop runs until the difference between x and y is less than a very small value (epsilon). This is to ensure accuracy in our results.

4. If the given number is negative, the function informs that the result will be a complex number. For simplicity, we do not calculate the complex result in this example.

5. Outside the functions, we get the input number from the user and calculate its square root using both methods.

6. The result is then displayed to the user.

7. The provided output section demonstrates the output for a sample input where the number is 25.

Comments