In: Computer Science
write a function to determine the square root of a number. The square root of a number can be approximated by repeated calculation using the formula NG = 0.5(LG + N/LG) where NG stands for the next guess and LG stands for the last guess. The loop should repeat until the difference between NG and LG is less than 0.00001. Use an initial guess of 1.0. Write a driver program to test your square root function. I WANT THIS PROGRAM IN PYTHON AND WIT PSEUDOCODE!!! AS SIMPLE AS POSSIBLE!!!!
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.
#code
PSEUDO-CODE FOR THE METHOD CALCULATING SQUARE ROOT MODULE square_root(num) DECLARE LG=1.0 DECLARE NG=(LG+(num/LG))/2 WHILE ABS(LG-NG) >= 0.00001 DO LG=NG NG=(LG+(num/LG))/2 END WHILE RETURN LG END MODULE
#PYTHON CODE FOR THIS PROBLEM INCLUDING TESTING
#required method to estimate the square root of num def square_root(num): #initializing 1 as initial guess LG=1.0 #calculating second term from LG NG=(LG+(num/LG))/2 #looping until the difference of prev and next is too small #(less than 0.00001) #note: use smaller values for more accurate results. while abs(LG-NG)>=0.00001: #storing current NG value as LG LG=NG #finding the next term NG = 0.5*(LG+ (num / LG)) #returning the value of LG at the end. return LG #main method for testing def main(): #reading a value n=float(input("Enter a number: ")) #displaying square root print('Square root is',square_root(n)) #calling main() main()
#OUTPUT
Enter a number: 5
Square root is 2.2360688956433634