Newton's method of calculating a square root.
★★☆5² = 25, so √25 = 5, or expressed another way, 5 * 5 = 25, so the square root of 25 is 5. Newton's method is one way to calculate the square root of a number.
Write a program that outputs the square root of a number using Newton’s method.
Remember to add a comment before a subprogram, selection or iteration statement to explain its purpose.
sqroot that:For example, the square root of 64 can be calculated in the sequence of steps:
64
32.5
17.234615384615385
10.474036101145005
8.292191785986859
8.005147977880979
8.000001655289593
8.00000000000017
8.0
8.0 – This value equals the previous value of root, so the algorithm is complete.
Enter a number: 25
The square root of 25.0 is 5.0
Enter a number: 64
The square root of 64.0 is 8.0
# Square root program
# -------------------------
# Subprograms
# -------------------------
# Function to calculate the square root of a number using Newton's method
---
def sqroot(x):
---
root = x
last_root = 0
---
while root != last_root:
---
last_root = root
---
root = 0.5 * (root + (x / root))
---
return root
---
# -------------------------
# Main program
# -------------------------
---
num = float(input("Enter a number: "))
---
print("The square root of", num, "is", sqroot(num))