《计算机科学和PYTHON编程导论》练习题
1.二分法:
# lecture 3.6, slide 2 # bisection search for square root x = 12345 epsilon = 0.01 numGuesses = 0 low = 0.0 high = x ans = (high + low)/2.0 while abs(ans**2 - x) >= epsilon: print('low = ' + str(low) + ' high = ' + str(high) + ' ans = ' + str(ans)) numGuesses += 1 if ans**2 < x: low = ans else: high = ans ans = (high + low)/2.0 print('numGuesses = ' + str(numGuesses)) print(str(ans) + ' is close to square root of ' + str(x))
练习题:
you (the user) thinks of an integer between 0 (inclusive) and 100 (not inclusive). The computer makes guesses, and you give it input - is its guess too high or too low? Using bisection search, the computer will guess the user's secret number!
secret=int(raw_input('Please input a number between 0 and 100:\n'))
low=0
high=100
ans=(low+high)/2
print'Is your secret number ' +str(ans)+'?'
i=raw_input()
while(i!='c'):
if i=='h':
high=ans
elif i=='l':
low=ans
else:
print'Sorry,I did not understand your input.Please do it again:'
ans=(low+high)/2
print'Is your secret number ' +str(ans)+'?'
i=raw_input()
print'I guessed correctly!'
2.牛顿-拉夫逊法
# Lecture 3.7, slide 3
# Newton-Raphson for square root
epsilon = 0.01
y = 24.0
guess = y/2.0
while abs(guess*guess - y) >= epsilon:
guess = guess - (((guess**2) - y)/(2*guess))
print(guess)
print('Square root of ' + str(y) + ' is about ' + str(guess))