You can calculate the square root of a number in Python without using the math
module by implementing your own algorithm. One popular method for approximating square roots is Newton’s method.
Python square root without math example
Here’s an example of how you can calculate the square root using this method:
def square_root(n):
# Initial guess for the square root
x = n / 2
# Iterate until desired precision is achieved
while True:
# Calculate a better approximation for the square root
y = (x + n / x) / 2
# Check if the approximation is close enough
if abs(y - x) < 1e-9:
return y
# Update the guess for the next iteration
x = y
# Example usage
number = 16
result = square_root(number)
print(f"The square root of {number} is approximately {result}")
This implementation starts with an initial guess for the square root (x = n / 2
) and iteratively improves the approximation by calculating y
as the average of x
and n / x
. It continues iterating until the difference between y
and x
is smaller than a predefined precision (1e-9
in this case), and then returns the final approximation.
If you don’t want to use the math
module in Python and prefer to avoid using the **
operator for exponentiation, you can calculate the square root using a loop and some basic arithmetic operations. Here’s an example:
def square_root(n):
# Handling special cases for 0 and 1
if n == 0 or n == 1:
return n
# Initial approximation for the square root
x = n / 2
# Iterate until desired precision is achieved
while True:
# Calculate the next approximation
y = 0.5 * (x + n / x)
# Check if the approximation is close enough
if abs(y - x) < 1e-9:
return y
# Update the approximation for the next iteration
x = y
# Example usage
number = 16
result = square_root(number)
print(f"The square root of {number} is approximately {result}")
Output:
This approach allows you to calculate square roots without relying on the math
module or the exponential operator **
, using basic arithmetic operations like division (/
), addition (+
), and absolute value (abs
).
Note: this method may not be as accurate or efficient as the one provided by the math
module, especially for large numbers or when higher precision is required. However, it can serve as a simple alternative if you prefer not to use the math
module.
Do comment if you have any doubts or suggestions on this Python code.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.