二分法&牛顿拉夫逊法
来源:互联网 发布:淘宝禁售手机充值了 编辑:程序博客网 时间: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
- 二分法&牛顿拉夫逊法
- 二分法与牛顿拉夫逊法基本思想
- 牛顿迭代法 二分法
- 二分法+牛顿下山法
- 二分法和牛顿迭代法
- 二分法与牛顿法
- 二分法、牛顿迭代法求sqrt()
- Sqrt(x) ,二分法,牛顿迭代法
- 【SPOJ-TRIGALGE】Easy Calculation【二分法】【牛顿迭代法】
- 二分法和牛顿法求平方根
- matlab二分法,单点弦截法,牛顿切线迭代法
- 习题- 二分法/牛顿迭代法 求算术平方根
- 二分法以及牛顿法开根号
- 方程求根(二分法和牛顿迭代法)
- [C]关于用二分法和牛顿迭代法求平方根
- 牛顿法与二分法的比较—matlab实现
- 【算法王道】二分法和牛顿迭代法求平方根
- 求平方根的方法(牛顿迭代法和二分法)
- 2-数字图像变换
- golang Garbage Collector(GC)
- 插入排序
- 使用ADB命令删除已安装应用
- 哈夫曼编码
- 二分法&牛顿拉夫逊法
- NetApp备份之SnapVault和SnapDiff技术
- [最小生成树]USACO 3.1 Agri-Net 最短网络
- HDU P2036 改革春风吹满地
- Kattis
- 坚持#第154天~突破瓶颈
- SSL 1618——剑鱼行动(最小生成树)
- Spring 使用七牛云存储上传图片以及html5图片压缩上传
- Tensorflow CIFAR-10训练例子报错解决