使用牛顿法求平方根(错误!) [英] Finding the square root using Newton's method (errors!)

查看:103
本文介绍了使用牛顿法求平方根(错误!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python中的牛顿的猜测和检查方法来完成一个数学问题,该问题近似于数字的平方根.用户应该输入一个数字,对该数字的初始猜测,以及他们想返回多少次才能检查答案.为了使事情变得更容易并了解Python(几个月前我才刚刚开始学习该语言),我将其分解为许多较小的函数.现在的问题是,我在调用每个函数并传递数字时遇到麻烦.

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, an initial guess for the number, and how many times they want to check their answer before returning. To make things easier and get to know Python (I've only just started learning the language a couple of months ago) I broke it up into a number of smaller functions; the problem now, though, is that I'm having trouble calling each function and passing the numbers through.

这是我的代码,提供注释以帮助您(每个功能按使用顺序排列):

Here is my code, with comments to help (each function is in order of use):

# This program approximates the square root of a number (entered by the user)
# using Newton's method (guess-and-check). I started with one long function,
# but after research, have attempted to apply smaller functions on top of each
# other.
# * NEED TO: call functions properly; implement a counting loop so the
# goodGuess function can only be accessed the certain # of times the user
# specifies. Even if the - .001 range isn't reached, it should return.

# sqrtNewt is basically the main, which initiates user input.

def sqrtNewt():
    # c equals a running count initiated at the beginning of the program, to
    # use variable count.
    print("This will approximate the square root of a number, using a guess-and-check process.")
    x = eval(input("Please type in a positive number to find the square root of: "))
    guess = eval(input("Please type in a guess for the square root of the number you entered: "))
    count = eval(input("Please enter how many times would you like this program to improve your initial guess: ")) 
    avg = average(guess, x)
    g, avg = improveG(guess, x)
    final = goodGuess(avg, x)
    guess = square_root(guess, x, count)
    compare(guess, x)


# Average function is called; is the first step that gives an initial average,
# which implements through smaller layers of simple functions stacked on each
# other.
def average(guess, x) :
    return ((guess + x) / 2)

# An improvement function which builds upon the original average function.
def improveG(guess, x) :
    return average(guess, x/guess)

# A function which determines if the difference between guess X guess minus the
# original number results in an absolute vale less than 0.001. Not taking
# absolute values (like if guess times guess was greater than x) might result
# in errors
from math import *
def goodGuess(avg, x) :
    num = abs(avg * avg - x)
    return (num < 0.001)

# A function that, if not satisfied, continues to "tap" other functions for
# better guess outputs. i.e. as long as the guess is not good enough, keep
# improving the guess.
def square_root(guess, x, count) :
    while(not goodGuess(avg, x)):
        c = 0
        c = c + 1
        if (c < count):
            guess = improveG(guess, x)
        elif (c == count):
            return guess
        else :
            pass

# Function is used to check the difference between guess and the sqrt method
# applied to the user input.
import math
def compare(guess, x):
    diff = math.sqrt(x) - guess
    print("The following is the difference between the approximation") 
    print("and the Math.sqrt method, not rounded:", diff)

sqrtNewt()

当前,我收到此错误:g, avg = improveG(guess, x) TypeError: 'float' object is not iterable. 最终函数使用猜测的最终迭代从数学平方根方法中减去,然后返回总差. 我什至在这样做对吗?如果可以的话,可以提供建议的工作代码,并提供一些建议.再说一次,我是新手,所以我为误解或明显的盲目的道歉.

Currently, I get this error: g, avg = improveG(guess, x) TypeError: 'float' object is not iterable. The final function uses the final iteration of the guess to subtract from the math square root method, and returns the overall difference. Am I even doing this right? Working code would be appreciated, with suggestions, if you can provide it. Again, I'm a newbie, so I apologize for misconceptions or blind obvious errors.

推荐答案

牛顿方法的实现:

在需要时对其进行一些微调应该很容易.尝试一下,告诉我们什么时候被卡住.

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

注意:您将在SO或谷歌搜索(但是)上找到足够的示例说明如何使用原始输入,如果您要计算循环,则c=0必须在循环之外,否则您将陷入无限循环

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又脏又脏,有很多改进方法:

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))

这篇关于使用牛顿法求平方根(错误!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆