二分法&牛顿拉夫逊法

来源:互联网 发布:淘宝禁售手机充值了 编辑:程序博客网 时间:2024/05/22 06:52

《计算机科学和PYTHON编程导论》练习题

1.二分法:

# lecture 3.6, slide 2# bisection search for square rootx = 12345epsilon = 0.01numGuesses = 0low = 0.0high = xans = (high + low)/2.0while 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.0print('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=0high=100ans=(low+high)/2print'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 rootepsilon = 0.01y = 24.0guess = y/2.0while abs(guess*guess - y) >= epsilon:    guess = guess - (((guess**2) - y)/(2*guess))    print(guess)print('Square root of ' + str(y) + ' is about ' + str(guess))



0 0