Python学习心得实例(2)

来源:互联网 发布:爱奇艺网络大电影排行 编辑:程序博客网 时间:2024/05/16 20:29

今天主要学习了是关于猜测数值的方法以及求值,一共有三种方法,分别是Newton Raphson, 二分法以及近似法等。
1. 二分法:

print("Please think of a number between 0 and 100!")# At the start the highest the number could be is 100 and the lowest is 0.hi = 100lo = 0guessed = False# Loop until we guess it correctlywhile not guessed:    # Bisection search: guess the midpoint between our current high and low guesses    guess = (hi + lo)/2    print("Is your secret number " + str(guess)+ "?")    user_inp = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")#注意raw_input的用法    if user_inp == 'c':        # We got it right!        guessed = True    elif user_inp == 'h':#即else+if=elif        # Guess was too high. So make the current guess the highest possible guess.        hi = guess    elif user_inp == 'l':        # Guess was too low. So make the current guess the lowest possible guess.        lo = guess    else:        print("Sorry, I did not understand your input.")print('Game over. Your secret number was: ' + str(guess))
  1. 求取平方根,用近似的方法
x = 25epsilon = 0.01step = epsilon**2numGuesses = 0ans = 0.0while (abs(ans**2 - x)) >= epsilon and ans <= x:ans += stepnumGuesses += 1print('numGuesses = ' + str(numGuesses))if abs(ans**2-x) >= epsilon:print('Failed on square root of ' + str(x))elseprint(str(ans) + ' is close to the square rootof ' + str(x))
  1. Newton Raphson:
epsilon = 0.01y = 24.0 #要求解的对象,目标是找到24的平方根guess = y/2.0while abs(guess*guess - y) >= epsilon:guess = guess - (((guess**2) - y)/(2*guess))print('Square root of ' + str(y) + ' is about '+ str(guess))
0 0
原创粉丝点击