How to write square root in Python
Python has a predefined sqrt() function that returns the square root of a number. It defines the square root of a value that multiplies itself to give a number. The sqrt() function is not used directly to find the square root of a given number, so we need to use a math module to call the sqrt() function in Python.
For example, the square root of 144 is 12.
1. Using the math.sqrt() Function
The math module in Python has a function math.sqrt() built for the square root of a number.
How it Works:
- The single argument has to be a non-negative number.
- The function returns the square root as a floating-point number.
Why Use math.sqrt():
- It is exact and made for this.
- For most real-number computations, involving square roots.
Example:
# Step 1: Import the math module
import math
# Step 2: Provide the number whose square root you want to calculate
number = 25
# Step 3: Use math.sqrt() to compute the square root
square_root = math.sqrt(number)
# Step 4: Display the result
print("The square root of", number, "is:", square_root)
Output:
The square root of 25 is: 5.0
2. Using the Exponentiation Operator (**)
This method relies on the mathematical rule that taking the square root of a number is the same as raising it to the power of 1/2.
Key Concept:
- The operator
**performs exponentiation in Python.
Why Use **:
- It doesn’t require importing any libraries.
- Very concise and Pythonic.
Example:
# Step 1: Provide the number
number = 36
# Step 2: Raise the number to the power of 0.5
square_root = number ** 0.5
# Step 3: Display the result
print("The square root of", number, "is:", square_root)
Output:
The square root of 36 is: 6.0
Tip: This method also works for calculating other roots (e.g., cube root, fourth root) by changing the exponent. For example,
x ** (1/3)gives the cube root.
3. Using the pow() Function
The pow() function is a built-in Python function that calculates x^y (x raised to the power of y).
Why Use pow():
- Similar to
**, but some programmers prefer the function for readability.
Example:
# Step 1: Provide the number
number = 49
# Step 2: Use the pow() function with 0.5 as the exponent
square_root = pow(number, 0.5)
# Step 3: Display the result
print("The square root of", number, "is:", square_root)
Output:
The square root of 49 is: 7.0
4. Using the numpy Library
The numpy library is a powerful scientific and numerical computing tool in Python. It comprises the numpy.sqrt() function.
Why Use numpy.sqrt():
- The function is quite good for working with large data sets and arrays.
- It is effective in scientific computations and projects in machine learning.
How to Use:
- Install
numpyif not already installed usingpip install numpy. - Use
numpy.sqrt()to find the square root.
Example:
# Step 1: Import the numpy library
import numpy as np
# Step 2: Provide the number
number = 64
# Step 3: Use numpy.sqrt() to calculate the square root
square_root = np.sqrt(number)
# Step 4: Display the result
print("The square root of", number, "is:", square_root)
Output:
The square root of 64 is: 8.0
Tip: You can also use
numpy.sqrt()on arrays to calculate square roots for multiple numbers simultaneously.
Example with Arrays:
# Using numpy to find square roots of multiple numbers
numbers = [4, 9, 16, 25]
square_roots = np.sqrt(numbers)
print("Square roots:", square_roots)
Output:
Square roots: [2. 3. 4. 5.]
5. Using the cmath Module for Complex Numbers
In mathematics, square roots of negative numbers are not defined for real numbers but exist in the realm of complex numbers. Python’s cmath (complex math) module allows you to handle such cases.
Why Use cmath.sqrt():
- It handles the real and imaginary parts of the square root.
- Automatically supports complex numbers.
Example:
# Step 1: Import the cmath module
import cmath
# Step 2: Provide a negative number
number = -9
# Step 3: Use cmath.sqrt() to calculate the square root
square_root = cmath.sqrt(number)
# Step 4: Display the result
print("The square root of", number, "is:", square_root)
Output:
The square root of -9 is: 3j
Explanation of Output:
- The result
3jrepresents 3×i, where i (denoted asjin Python) is the imaginary unit.
What Happens if You Input Invalid Data?
Negative Numbers with math.sqrt():
import math
try:
print(math.sqrt(-4))
except ValueError as e:
print("Error:", e)
Output:
Error: math domain error
Non-Numeric Inputs:
If you pass a string or any non-numeric value to any of these methods, Python will raise a TypeError.
Recap of Methods and Their Usage:
| Method | Pros | Cons |
|---|---|---|
math.sqrt() | Simple and accurate for real numbers | Cannot handle negative numbers |
** 0.5 | Quick and does not need imports | Less readable for beginners |
pow() | Built-in, readable | Same as **, no special advantages |
numpy.sqrt() | Great for arrays and large computations | Requires numpy library installation |
cmath.sqrt() | Handles complex numbers automatically | Unnecessary for real-only calculations |
Final Tips:
- For everyday use, stick with
math.sqrt()or** 0.5. - Use
numpywhen working with large datasets or arrays. - Use
cmathfor complex numbers.