In this post, you will learn how to calculate the square root in Python. A square root is a standard mathematical operation you can use to solve quadratic equations or calculate the length of one side of a right-angled triangle. There are several ways of calculating the square root, using exponentiation, with the math and NumPy sqrt() functions. I will discuss the pros and cons of each method, so you can start solving your mathematics equations as a Python expert!

## Table of contents

## What is a Square Root in Mathematics?

In algebra, a square of a number is the result of a number, n, multiplied by itself.

```
n = 3
x = n ** 2
print(x)
```

```
9
```

The Python ** operator calculates the power of a number. In the case shown, the number 3 is raised to the power of 2, which is 9. Therefore, the square root is the number n, which, when multiplied by itself, produces the square x. In the example shown, the square root of 9 is 3. 9 is an example of a perfect square, squares of integer values.

## The Exponentiation Operator **0.5

Using the exponentiation operator ** is a straightforward way to obtain the square root of a number. As shown in the previous section, it raises the first number to the power of the second number.

To obtain the square root, the power to use is 0.5. I have shown an example of how you can use ** 0.5 to calculate the square root for a range of perfect square numbers.

```
squares = [9, 16, 25, 36, 49, 81]
for x in squares:
sqrt_x = x ** 0.5
print(f'value:{x} square root is {sqrt_x}')
```

```
value: 9 square root is 3.0
value: 16 square root is 4.0
value: 25 square root is 5.0
value: 36 square root is 6.0
value: 49 square root is 7.0
value: 81 square root is 9.0
```

You can use the exponentiation operator to calculate the absolute value of a number. As the absolute value of a real number $latex x$ is $latex \sqrt{x^{2}}$.

## math.sqrt()

Python’s standard library math can help you solve mathematical problems in code. There are various useful functions inside the module including trigonometric and logarithmic functions. It also includes the Python square root function, sqrt(). To use the function, you have to import math first:

`import math`

We can replace the exponentiation operator with sqrt() to calculate the square roots. The function takes one parameter, x, which stands for the square you want to find the square root of. You can see the function in use below:

```
squares = [9, 16, 25, 36, 49, 81]
for x in squares:
sqrt_x = math.sqrt(x)
print(f'value:{x} square root is {sqrt_x}')
```

```
value: 9 square root is 3.0
value: 16 square root is 4.0
value: 25 square root is 5.0
value: 36 square root is 6.0
value: 49 square root is 7.0
value: 81 square root is 9.0
```

The return value of sqrt() is the square root of x, as a floating-point number. The values are the same as those obtained with the exponentiation operator. The benefit of using the exponentiation operator is that it does not require a module import. However, math.sqrt() typically is the faster function as demonstrated by developers in this Stack Overflow answer.

## numpy.sqrt()

You can store numbers in NumPy arrays and perform mathematical operations on all of the elements in the array. In the case of the square root function, you can use numpy.sqrt(). To use NumPy, you have to import NumPy. Typically, developers use the alias for NumPy, np:

```
import numpy as np
```

First, you have to define your values in a NumPy array. The sqrt() function will create a new array containing the square roots of the original array. The example below shows how this operation can be done:

```
squares_array = np.array([9, 16, 25, 36, 49, 81])
sqrt_array = np.sqrt(squares_array)
print(f'values: {squares_array} square root of values are: {sqrt_array}')
```

```
values: [ 9 16 25 36 49 81] square root of values are: [3. 4. 5. 6. 7. 9.]
```

You can use the square root function, np.sqrt() on single values, but NumPy is optimized for operations on arrays, so preferably use the function on arrays only.

## The Square Root of Negative Numbers

It is impossible to produce negative squares of real numbers. This is because a negative product is only possible if one operand is positive and the other is negative. A square, by definition, is the product of a number with itself. If you try to calculate the square root of a negative number using the math module, you will throw a ValueError as shown below:

```
math.sqrt(-4)
```

```
ValueError Traceback (most recent call last)
1 math.sqrt(-4)
ValueError: math domain error
```

You may want to keep the ValueError depending on how you want to handle the square root of negatives. You can avoid ValueError by using the exponentiation operator or cmath.sqrt().

For further reading on ValueError: math domain error, go to the article How to Solve Python ValueError: math domain error.

When using the exponentiation operator, ensure that the negative value is in parentheses:

```
import cmath
```

```
negative_squares = [-4, -9, -16, -25, -36]
for x in negative_squares:
x_sqrt = (x) ** 0.5
print(f'value: {x} square root is: {x_sqrt}')
```

```
value: -4 square root is: (1.2246467991473532e-16+2j)
value: -9 square root is: (1.8369701987210297e-16+3j)
value: -16 square root is: (2.4492935982947064e-16+4j)
value: -25 square root is: (3.061616997868383e-16+5j)
value: -36 square root is: (3.6739403974420594e-16+6j)
```

The values produced are complex numbers, which are the sum of a real and imaginary number. To calculate the square root of negative and complex numbers using the cmath library, first import it then you can use the sqrt() function, similar to the math library.

```
import cmath
# Square root of negative number
negative_square = -4
# Square root of complex mumber
complex_number = (4 + 16j)
negative_sqrt = cmath.sqrt(negative_square)
complex_sqrt = cmath.sqrt(complex_number)
print(negative_sqrt, '\n', complex_sqrt)
```

```
2j
(4+2j)
```

Now that you know how to use cmath.sqrt(), you can apply it as a way to handle exceptions, for example in the following script:

```
mixed_squares = [9, -16, 25, -36, 81]
for x in mixed_squares:
try:
x_sqrt = math.sqrt(x)
except ValueError:
x_sqrt = cmath.sqrt(x)
print(f'value: {x} square root is {x_sqrt}')
```

```
mixed_squares = [9, -16, 25, -36, 81]
value: 9 square root is 3.0
value: -16 square root is 4j
value: 25 square root is 5.0
value: -36 square root is 6j
value: 81 square root is 9.0
```

## Real World Example of Square Roots

The square root function is everywhere! For example, there are many formulae in physics and engineering that use the square root. The distance that a free-falling object has fallen after a time *t* seconds is given by the formula:

**$latex x = \frac{gt^{2}}{2}$**.

With some rearranging, we can get the time for a free-falling object to fall a certain distance using:

$latex t = \sqrt{\frac{2x}{g}}$.

Where *g * is the acceleration of gravity (9$latex \text{ms}^{2}$). If you were to drop a tennis ball off the top of a building 100 metres high, you can calculate the time the ball would take to hit the ground with the following script. Firstly you can access *g* using scipy, which is a popular scientific computing library. For more popular Python libraries, you can visit my blog post titled “Top 12 Python Libraries for Data Science and Machine Learning“.

```
from scipy import constants
g = constants.g
x = 100
t = math.sqrt( ( 2 * x ) / g )
print(f'time taken to fall {x} metres is {t} seconds')
```

```
time taken to fall 100 metres is 4.5160075575178755 seconds
```

## Summary

Congratulations on learning how to use the Python square root function. You now know:

- The premise of squares and the square root.
- The application of the square root to real and complex numbers.
- The application of the square to negative numbers.
- The different ways to calculate the square root including exponentiation operator, math, cmath, and numpy.
- A real world example of the square root function.

For further reading on mathematical operations in Python, go to the article: How to Multiply Two Matrices in Python.

Stay tuned for more articles covering common Python questions relevant to data science and machine learning. You can visit another Python Solutions article, such as how to search for a substring in a string. For a more in-depth exploration of Python specifically for data science and machine learning, you can visit the Python Online Course page. Have fun applying your newly acquired square root function knowledge!

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.