Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to square root in Python

Introduction

If you're learning programming, you might have come across the term "square root" in mathematics. In this blog, we'll learn about square root, why it's important, and how to calculate square roots using Python programming.

Square root is a mathematical term that represents the number that, when multiplied by itself, would give the original number. For example, the square root of 25 is 5 because 5 * 5 = 25. In mathematical notation, the square root of a number x is represented as √x or x^(1/2).

In Python, we can calculate the square root of a number using various methods. We'll explore some of these methods in this blog.

Built-in Python Functions

Python provides built-in functions and libraries to perform mathematical operations such as square roots. The math library is one such library that contains various functions to perform mathematical operations, including square roots.

Using the math.sqrt() function

Let's start by importing the math library and using the math.sqrt() function to find the square root of a number.

import math

number = 25
square_root = math.sqrt(number)

print("The square root of", number, "is", square_root)

Output:

The square root of 25 is 5.0

As you can see, the math.sqrt() function calculates the square root of the given number and returns the result as a floating-point number.

Using the exponentiation operator (**)

Another way to find the square root of a number in Python is by using the exponentiation operator (**). The square root of a number x can be represented as x^(1/2).

number = 25
square_root = number ** 0.5

print("The square root of", number, "is", square_root)

Output:

The square root of 25 is 5.0

In this example, we've used the exponentiation operator to raise the number to the power of 0.5, which is the same as finding the square root.

Implementing Your Own Square Root Function

You may be wondering, "How does Python calculate the square root internally?" Although the internal implementation of the math.sqrt() function might be different, we can implement our own function to calculate the square root of a number using well-known algorithms.

In this section, we'll learn how to implement two popular algorithms for finding square roots – the Babylonian method and the Newton-Raphson method.

The Babylonian Method

The Babylonian method, also known as Heron's method, is an ancient algorithm used to find the square root of a number. The algorithm starts with an initial guess and iteratively refines the guess until it converges to the actual square root. Here's the algorithm in a nutshell:

  1. Start with an initial guess x0.
  2. Calculate the next guess x1 using the formula: x1 = (x0 + (number / x0)) / 2.
  3. Repeat step 2 until the difference between the current guess and the previous guess is smaller than a predefined threshold.

Let's implement the Babylonian method in Python:

def babylonian_sqrt(number, threshold=1e-10):
    if number < 0:
        raise ValueError("Square root not defined for negative numbers")

    guess = number
    while True:
        next_guess = (guess + (number / guess)) / 2
        if abs(guess - next_guess) < threshold:
            return next_guess
        guess = next_guess

number = 25
square_root = babylonian_sqrt(number)

print("The square root of", number, "is", square_root)

Output:

The square root of 25 is 5.000000000053722

As you can see, our implementation of the Babylonian method successfully finds the square root of the given number.

The Newton-Raphson Method

The Newton-Raphson method is a more general numerical method used to find the roots of a real-valued function. It can also be used to find the square root of a number by considering the function f(x) = x^2 - number. The algorithm is similar to the Babylonian method, but it uses a different formula to refine the guess:

  1. Start with an initial guess x0.
  2. Calculate the next guess x1 using the formula: x1 = x0 - f(x0) / f'(x0), where f'(x0) is the derivative of f(x) with respect to x.
  3. Repeat step 2 until the difference between the current guess and the previous guess is smaller than a predefined threshold.

Let's implement the Newton-Raphson method in Python:

def newton_raphson_sqrt(number, threshold=1e-10):
    if number < 0:
        raise ValueError("Square root not defined for negative numbers")

    guess = number
    while True:
        next_guess = guess - ((guess ** 2 - number) / (2 * guess))
        if abs(guess - next_guess) < threshold:
            return next_guess
        guess = next_guess

number = 25
square_root = newton_raphson_sqrt(number)

print("The square root of", number, "is", square_root)

Output:

The square root of 25 is 5.000000000000053

As you can see, our implementation of the Newton-Raphson method also successfully finds the square root of the given number.

Conclusion

In this blog, we have learned about square roots and how to calculate them using Python programming. We've explored different ways to find the square root of a number, including built-in functions, the exponentiation operator, and implementing our own square root functions using the Babylonian and Newton-Raphson methods.

The built-in math.sqrt() function and the exponentiation operator are the most straightforward and efficient ways to find the square root of a number in Python. However, implementing your own square root function can be a great exercise to improve your understanding of numerical methods and algorithms.

As you continue to learn programming, remember to experiment with different methods and algorithms to solve problems, as it will help you become a better programmer in the long run. Happy coding!