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))
- 求取平方根,用近似的方法
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))
- 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
- Python学习心得实例(2)
- Python学习心得实例(1)
- python学习心得实例(3)
- think python学习心得-(2)接口设计
- python学习心得(2) --- xml解析
- Python学习心得(1)
- python学习心得(1)
- Python学习心得(一)类型
- Python学习心得
- Python 学习心得
- python 学习心得
- python学习心得
- Python学习心得
- python学习心得
- Python学习心得
- python 学习心得
- python学习心得一(迭代)
- 学习心得(2)
- 黑马程序员-[JAVA基础]-23种设计模式之单例设计模式
- iOS开发-文件管理之多的是你不知道的事(一)
- 用户crontab不执行的解决方法
- Java内存——基本知识
- javaScript实现日历控件
- Python学习心得实例(2)
- win7 64位机器上 为Notepad++ 配置 vs 编译器
- Django中的数据记录的增、删、改、查
- Linux——虚拟目录
- 本人有一串代码没看懂,请人帮忙注释发我邮箱
- Dubbo框架应用之(四)--Dubbo基于Zookeeper实现分布式实例
- Java IO
- js实现表格排序(正序和反序)
- [SQL SERVER] 實戰紀錄 使用資料壓縮技術 (Page Compression、Row Compression)