MIT 6.00.1X --Week 3

NEWTON-RAPHSON ROOT FINDING


  • General approximation algorithm to find roots of a
    polynomial in one variable

p(x)=anxn+an1xn1++a1x+a0

  • Want to find r such that p(r) = 0
  • Newton showed that if g is an approximation to the
    root, then
    gp(g)/p(g)
    is a better approximation; where p’ is derivative of p.
# Lecture 3.7, slide 3

# Newton-Raphson for square root

epsilon = 0.01
y = 24.0
guess = y/2.0

while abs(guess*guess - y) >= epsilon:
    guess = guess - (((guess**2) - y)/(2*guess))
    print(guess)
print('Square root of ' + str(y) + ' is about ' + str(guess))

# lecture 3.6, slide 2
# bisection search for square root

x = 12345
epsilon = 0.01
numGuesses = 0
low = 0.0
high = x
ans = (high + low)/2.0
while 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.0
print('numGuesses = ' + str(numGuesses))
print(str(ans) + ' is close to square root of ' + str(x))

普通迭代

x = 25
epsilon = 0.01
step = 0.1
guess = 0.0

while guess <= x:
    if abs(guess**2 -x) < epsilon:
        break
    else:
        guess += step

if abs(guess**2 - x) >= epsilon:
    print 'failed'
else:
    print 'succeeded: ' + str(guess)

FLOATING POINT ACCURACY


浮点数的二进制表示与还原

先挖个坑。。。
参考《计算机专业导论之思维与系统》

你可能感兴趣的:(计算机导论)