标签:python
>>> a = 2 ** 1000
>>> a
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376L
>>> b = 2 ** 999
>>> b
5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688L
>>> a/b
2L
IEEE 754 floating point
wiki IEEE floating point
wiki IEEE 754 中文
a mantissa 尾数(0=< mantissa < 2) and an exponent 指数
worry about == on float number!
>>> import math
>>> a = math.sqrt(2)
>>> a
1.4142135623730951
>>> a * a == 2
False
# 大约相等
abs(a*a - 2.0) < epsilon
>>> s = 0.0
>>> for i in range(10): s += 0.1
...
>>> s
0.9999999999999999
Why might this be a challenge? What are some of the issues?
# 逐次逼近法(伪代码):
guess = inital guess
for iter in range(100):
if f(guess) close enough: return guess
else: guess = better guess
error
逐次逼近法求平方根
- 二分法,求x的平方根,epsilon (ε) 是一个足够小的数,ctr 迭代次数
def squareRootBi(x, epsilon):
"""Assume x >= 0 and epsilon > 0
Return y s.t. y*y is within epsilon(ε) of x"""
assert epsilon > 0, ‘epsilon must be postive, not‘ + str(epsilon)
low = 0
high = max(x, 1)
guess = (low + high) / 2.0
ctr = 1
while abs(guess ** 2 - x) > epsilon and ctr <= 100:
# print ‘low:‘, low, ‘high:‘, high, ‘guess:‘, guess if guess**2 < x:
if guess**2 < x:
low = guess
else:
high = guess
guess = (low + high) / 2.0
ctr += 1
assert ctr <= 100, ‘Iteration count exceeded‘
print ‘Bi method. Num. iterations:‘, ctr, ‘Estimate:‘, guess
return guess
def squareRootNR(x, epsilon):
"""Return y s.t. y*y is within epsilon of x"""
assert epsilon > 0, ‘epsilon must be postive, not‘ + str(epsilon)
x = float(x)
guess = x / 2.0
guess = 0.001
diff = guess ** 2 - x
ctr = 1
while abs(diff) > epsilon and ctr <= 100:
# print ‘Error:‘, diff, ‘guess:‘, guess guess = guess - diff/(2.0*guess)
diff = guess ** 2 - x
ctr += 1
assert ctr <= 100, ‘Iteration count exceeded‘
print ‘NR method. Num. iterations:‘, ctr, ‘Estimate:‘, guess
return guess
MIT公开课:计算机科学及编程导论 Python 笔记5 浮点数,逐次逼近法和二分法
标签:python
原文地址:http://blog.csdn.net/muzilanlan/article/details/45825025