Finding the square root using Newton's method (errors!)

前端 未结 5 1516
执念已碎
执念已碎 2020-12-11 10:06

I\'m working to finish a math problem that approximates the square root of a number using Newton\'s guess and check method in Python. The user is supposed to enter a number,

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 10:47

    Implementation of the newton method:

    It should be fairly easy to add little tweaks to it when needed. Try, and tell us when you get stuck.

    from math import *
    def average(a, b):
        return (a + b) / 2.0
    def improve(guess, x):
        return average(guess, x/guess)
    def good_enough(guess, x):
        d = abs(guess*guess - x)
        return (d < 0.001)
    def square_root(guess, x):
        while(not good_enough(guess, x)):
            guess = improve(guess, x)
        return guess
    def my_sqrt(x):
        r = square_root(1, x)
        return r
    
    >>> my_sqrt(16)
    4.0000006366929393
    

    NOTE: you will find enough exaples on how to use raw input here at SO or googling, BUT, if you are counting loops, the c=0 has to be outside the loop, or you will be stuck in an infinite loop.

    Quiqk and dirty, lots of ways to improve:

    from math import *
    def average(a, b):
        return (a + b) / 2.0
    def improve(guess, x):
        return average(guess, x/guess)
    def square_root(guess, x, c):
        guesscount=0
        while guesscount < c :
            guesscount+=1
            guess = improve(guess, x)
        return guess
    def my_sqrt(x,c):
        r = square_root(1, x, c)
        return r
    
    number=int(raw_input('Enter a positive number'))
    i_guess=int(raw_input('Enter an initial guess'))
    times=int(raw_input('How many times would you like this program to improve your initial guess:'))    
    answer=my_sqrt(number,times)
    
    print 'sqrt is approximately ' + str(answer)
    print 'difference between your guess and sqrt is ' + str(abs(i_guess-answer))
    

提交回复
热议问题