Square Root Calculator Python with Math
How to Calculate Square Roots in Python
Calculating square roots in Python is straightforward using the built-in math module. The square root of a number is the value that, when multiplied by itself, gives the original number.
For real numbers, use math.sqrt(). For complex numbers, use cmath.sqrt(). Here's how to implement both:
Python Square Root Code Examples
import math
import cmath
# Real number square root
real_num = 16
real_sqrt = math.sqrt(real_num)
print(f"Square root of {real_num} is {real_sqrt}")
# Complex number square root
complex_num = -16
complex_sqrt = cmath.sqrt(complex_num)
print(f"Square root of {complex_num} is {complex_sqrt}")
The math.sqrt() function returns a float, while cmath.sqrt() returns a complex number. Both functions raise a ValueError if given a negative number to math.sqrt().
Square Root Formula
The square root of a number \( x \) is a value \( y \) such that:
Square Root Formula
\( y = \sqrt{x} \) where \( y^2 = x \)
For real numbers, \( x \) must be non-negative. For complex numbers, the formula extends to:
Complex Square Root Formula
\( \sqrt{x} = \pm \sqrt{\frac{|x|}{2}} \pm i \sqrt{\frac{|x|}{2}} \)
Where \( i \) is the imaginary unit (\( i^2 = -1 \)).
Worked Examples
Example 1: Real Number Square Root
Calculate the square root of 25:
Using Python:
import math
print(math.sqrt(25)) # Output: 5.0
Example 2: Complex Number Square Root
Calculate the square root of -9:
Using Python:
import cmath
print(cmath.sqrt(-9)) # Output: 3j
This returns \( 3i \) because \( (3i)^2 = -9 \).
Frequently Asked Questions
- What is the difference between math.sqrt() and cmath.sqrt()?
math.sqrt()works only with real numbers and returns a float.cmath.sqrt()works with complex numbers and returns a complex number.- Can I calculate the square root of a negative number with math.sqrt()?
- No,
math.sqrt()raises aValueErrorfor negative numbers. Usecmath.sqrt()instead. - How accurate are Python's square root calculations?
- Python uses IEEE 754 double-precision floating-point arithmetic, which provides about 15-17 significant decimal digits of precision.
- Can I calculate the square root of a matrix in Python?
- Yes, you can use libraries like NumPy's
numpy.linalg.sqrtm()function for matrix square roots.