Python program find the square root of a number (Newton’s method)
Here you will get an example to write a Python program find the square root of a number Newtons method.
Example Python program find the square root of a number Newtons method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | def newtons_method_sqrt(number, tolerance=1e-10, max_iterations=1000): if number < 0: raise ValueError("Cannot compute the square root of a negative number.") guess = number for _ in range(max_iterations): next_guess = 0.5 * (guess + number / guess) if abs(next_guess - guess) < tolerance: return next_guess guess = next_guess return guess def main(): try: number = float(input("Enter a number to find its square root: ")) if number < 0: print("Cannot compute the square root of a negative number.") return result = newtons_method_sqrt(number) print(f"The square root of {number} is approximately {result}") except ValueError: print("Please enter a valid number.") if __name__ == "__main__": main() |
Output
Enter a number to find its square root: 16
The square root of 16.0 is approximately 4.0
Check out our other Python programming examples