Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to do square root in Python

Introduction

Welcome to this tutorial! As a budding programmer, you might have come across the need to find the square root of a number in your coding journey. In this tutorial, we will explore how to find the square root of a number in Python. We will start with some basics and then dive into different approaches, along with code examples, to help you understand the concepts better.

Square Root: What is it?

Before we jump into the code, let's understand what a square root is. In mathematics, the square root of a number is a value that, when multiplied by itself, gives the original number. For example, the square root of 9 is 3 because 3 * 3 = 9. Similarly, the square root of 16 is 4 because 4 * 4 = 16. You might have noticed that we are using only positive numbers as examples. That's because we are dealing with real numbers in this tutorial, and real numbers have non-negative square roots.

Now that we have a basic understanding of square roots let's look at how to find them in Python.

Python's Built-In "math" Library

Python provides a built-in library called math that contains various mathematical functions, including one to find the square root of a number. The math library has a function called sqrt() that takes a number as an input and returns its square root.

Here's how you can use the sqrt() function to find the square root of a number:

import math

number = 9
square_root = math.sqrt(number)
print(f"The square root of {number} is {square_root}.")

Output:

The square root of 9 is 3.0.

In this example, we first import the math library, and then we use the sqrt() function to find the square root of 9. The sqrt() function returns the square root as a float, which we then print to the console.

Now, let's understand another approach to find the square root of a number using the exponentiation operator.

Exponentiation Operator

Python provides an exponentiation operator (**) that you can use to raise a number to a specified power. To find the square root of a number using the exponentiation operator, you can raise the number to the power of 0.5, as the square root of a number is the same as raising it to the power of 0.5.

Here's an example:

number = 16
square_root = number ** 0.5
print(f"The square root of {number} is {square_root}.")

Output:

The square root of 16 is 4.0.

In this example, we find the square root of 16 by raising it to the power of 0.5. The result is a float, which we then print to the console.

Now that we have seen two approaches to finding the square root of a number let's look at a more complex method that can help you better understand the underlying concepts.

Square Root Using 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 method starts with an initial guess and iteratively refines the guess until it converges to the actual square root.

Here's the algorithm for the Babylonian method:

  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 using the new guess x1 until the difference between the current guess and the previous guess is smaller than a specified tolerance value.

Now, let's implement the Babylonian method in Python:

def babylonian_method(number, tolerance=1e-10):
    if number < 0:
        raise ValueError("Square root not defined for negative numbers.")
    guess = number
    while abs(guess * guess - number) > tolerance:
        guess = (guess + number / guess) / 2
    return guess

number = 25
square_root = babylonian_method(number)
print(f"The square root of {number} is {square_root}.")

Output:

The square root of 25 is 5.0.

In this example, we first define a function babylonian_method() that takes a number and an optional tolerance value as inputs. The function starts with an initial guess equal to the input number and then iteratively refines the guess using the Babylonian method algorithm. The function returns the final guess as the square root of the input number.

We can then use the babylonian_method() function to find the square root of 25, as shown in the example.

Comparing the Approaches

Now that we have seen three different approaches to finding the square root of a number in Python let's compare them in terms of performance and use cases.

math.sqrt(): This is the easiest and most straightforward approach. It's also the fastest method since it's a built-in function that is optimized for performance. Use this method when you need to quickly find the square root of a number and don't need to implement the algorithm yourself.

Exponentiation operator: This approach is also quite simple and easy to understand. It's slightly slower than the math.sqrt() function but still quite fast for most use cases. Use this method when you want a one-liner solution without importing any external libraries.

Babylonian method: This method is more complex and slower than the other two approaches. However, it can help you gain a deeper understanding of the underlying concepts and algorithms used to find the square root of a number. Use this method when you need to implement a custom square root algorithm, or when you want to learn more about the mathematics behind finding square roots.

Conclusion

In this tutorial, we have learned how to find the square root of a number in Python using three different approaches: the built-in math.sqrt() function, the exponentiation operator, and the Babylonian method. We have also discussed the advantages and use cases of each approach.

As a beginner in programming, it's essential to understand the underlying concepts and algorithms behind the code. This will not only help you become a better programmer but also enable you to solve more complex problems in the future. So, don't shy away from exploring different approaches and digging deeper into the mathematics behind the code. Happy coding!