s

Problem7



Write a program that that takes a positive floating point number as input and outputs an approximation of its square root.


while True:
    try:
        rootof = float(input("Please enter a positive floating point number: ")) 
        if rootof < 0:
          
           raise ValueError
       
        break  

    except ValueError:
        print("That was not a positive floating point number. Please try again")


estimate  = 10


while abs((estimate * estimate) - rootof )> 0.01:

    estimate -=((estimate * estimate)-rootof)/(2 * estimate)    
 
sqroot = estimate    
    
# using the math module's sqrt function
import math

#print(f"The square root of {rootof} is approx. {math.sqrt(rootof)}.")

print(f"The square root of {rootof} is approx. {sqroot:.1f}")

Using Newtons Method, regardless of the starting estimate, once the square of the estimate gets close enough (I used 0.01 for this program) to the actual number itself, then that is a good approximation for the square root. An intial estimate is used for the square root. This can be any number to start the loop going as the while loop will keep changing the estimate until it is close enough, here within 0.01.

Python logo

Tech used:
  • Python
  • math module
  • abs