The “divide and average” method, an old-time method for approximating the square
ID: 3783190 • Letter: T
Question
The “divide and average” method, an old-time method for approximating the square root of any positive number a, can be formulated as
x =( x + (a/x)) / 2
Write a well-structured python function to implement this algorithm based on the outlined algorithm below. The program must take as input the following values:
• The value whose square root is sought, a
• An initial guess of the solution, xguess
• The number of decimals, n, in order to calculate the error criteria, es
• The maximum number of iterations allowed before declaring a diverging solution, maxit
The program should produce, as output, the value of the error criteria, es, and a table showing the different iterations required to find a solution using the required error criteria.
Show the results of your program for a = 122.5, xguess = 5.0, n = 5, maxit = 20.
Iterative ProcedureHints (1) I E Numerical Methods fol x E ENGR2450Assignment 1.pd O file:///C/Users/canad/Downloads/Numerical Methods for Engineers- 7th-Edition steven chapra.pdf 80 of 987 3.3 ERROR DEFINITIONS FUNCTION IterMeth val, es maxit) iter 1 sol va 100 DO solo 1d sol soil iter iter 1 IF sol E 0 ea abs (sol so 101d)/ Sol) *100 IF ea s es OR iter maxit EXIT END DO IterMeth sol END I terMeth Ask me anything 12:44 PM 1/24/2017 XExplanation / Answer
Python 2.7 Code:
print "Please Enter The value whose square root is sought"
a = float(raw_input().strip())
print "Please Enter An initial guess of the solution"
x_guess = float(raw_input().strip())
print "Please Enter The number of decimals for error criteria"
es = int(raw_input().strip())
print "Please Enter The maximum number of iterations "
maxit = int(raw_input().strip())
x = a
y = 1
error = float(1.0)/float(10.0**es)
it = 0
while(x-y > error and it < maxit):
it = it + 1
x = (x+y)/2
y = a/x
print "value of square root in ", it, " iterations", " is ", x
print "Error criteria is Update in value of square root should be less than ", error
print "Square root of ",a, " is ", x
Sample Output:
Please Enter The value whose square root is sought
16
Please Enter An initial guess of the solution
3.5
Please Enter The number of decimals for error criteria
2
Please Enter The maximum number of iterations
5
value of square root in 1 iterations is 8.5
value of square root in 2 iterations is 5.19117647059
value of square root in 3 iterations is 4.13666472255
value of square root in 4 iterations is 4.0022575248
Error criteria is Update in value of square root should be less than 0.01
Square root of 16.0 is 4.0022575248
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.