我正在使用Python中的牛頓猜測和檢查方法來完成一個近似數字的平方根的數學問題。用戶應該輸入一個數字,初始猜測數字,以及他們想要在返回之前檢查他們的答案的次數。爲了讓事情變得更容易,並且瞭解Python(幾個月前我纔剛剛開始學習這門語言),我將它分解爲一些較小的函數;現在的問題是,我無法調用每個函數並傳遞數字。使用牛頓的方法找到平方根(錯誤!)
這裏是我的代碼,與意見,以幫助(每個功能在使用順序排列):
# 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.
最終的功能使用的猜測最終迭代從數學平方根法減去,並返回整體差異。 我是否做對了?工作代碼將不勝感激,並提供建議,如果你可以提供。再次,我是一個新手,所以我對錯誤觀念或盲目的明顯錯誤表示歉意。
有你看着http://radiantbytes.com/books/python-latex/src/chap9.html - 這一切都沒有:) – root