首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用牛顿方法求平方根(错误!)

用牛顿方法求平方根(错误!)
EN

Stack Overflow用户
提问于 2012-10-12 07:25:01
回答 5查看 28.1K关注 0票数 2

在Python中,我正在使用牛顿的猜测和检查方法来完成一道近似数字平方根的数学题。用户应该输入一个数字,对该数字的初始猜测,以及他们想要在返回之前检查答案的次数。为了让事情变得更简单并了解Python (我几个月前才开始学习这门语言),我把它分成了几个较小的函数;但现在的问题是,我在调用每个函数和传递数字时遇到了麻烦。

这是我的代码,带有帮助注释(每个函数都是按使用顺序排列的):

代码语言:javascript
运行
复制
# 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.最终函数使用猜测的最终迭代从数学平方根方法中减去,并返回总差值。我这样做是对的吗?工作代码将不胜感激,建议,如果你能提供它。再说一次,我是一个新手,所以我为误解或盲目的明显错误道歉。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2012-10-12 07:37:26

牛顿法的实现:

在需要的时候添加一些小的调整应该是相当容易的。试试看,当你卡住的时候告诉我们。

代码语言:javascript
运行
复制
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或googling中,你会找到足够多的关于如何使用原始输入的例子,但是,如果你在计算循环,c=0必须在循环之外,否则你会陷入无限循环。

Quiqk和脏,有很多改进的方法:

代码语言:javascript
运行
复制
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))
票数 9
EN

Stack Overflow用户

发布于 2013-03-08 10:13:40

选择的答案是对OP有点convoluted...no不尊重。

对于将来用谷歌搜索这个的人来说,这是我的解决方案:

代码语言:javascript
运行
复制
def check(x, guess):
    return (abs(guess*guess - x) < 0.001)

def newton(x, guess):
    while not check(x, guess):
        guess = (guess + (x/guess)) / 2.0
    return guess

print newton(16, 1)
票数 7
EN

Stack Overflow用户

发布于 2012-10-12 10:11:12

下面是一个非常不同的计算平方根的函数;它假设n是非负的:

代码语言:javascript
运行
复制
def mySqrt(n):
    if (n == 0):
        return 0
    if (n < 1):
        return mySqrt(n * 4) / 2
    if (4 <= n):
        return mySqrt(n / 4) * 2
    x = (n + 1.0) / 2.0
    x = (x + n/x) / 2.0
    x = (x + n/x) / 2.0
    x = (x + n/x) / 2.0
    x = (x + n/x) / 2.0
    x = (x + n/x) / 2.0
    return x

此算法类似于牛顿的算法,但不完全相同。它是由一位名叫Heron (他的名字有时拼写为Hero)的希腊数学家发明的,他住在公元一世纪(大约两千年前)的埃及亚历山大。Heron的递归公式比牛顿的递归公式简单;Heron使用x' = (x + n/x) / 2,而牛顿使用x' = x - (x^2 - n) / 2x

第一个测试是0的特例;如果没有它,(n < 1)测试将导致无限循环。接下来的两个测试将n归一化为范围1 < n <= 4;使范围变小意味着我们可以轻松地计算n的平方根的初始近似值,这是在第一次计算x时完成的,然后“展开循环”并将递归方程迭代固定次数,从而在两个连续循环之间的差异太大时消除测试和递归的需要。

顺便说一句,Heron是个很有趣的家伙。除了发明了一种计算平方根的方法外,他还发明了一台可以工作的喷气式发动机,一台投币式自动售货机,以及许多其他整洁的东西!

你可以在my blog上阅读更多关于计算平方根的内容。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12850100

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档