Skip to content

Instantly share code, notes, and snippets.

@yao2030
Created April 4, 2013 06:07
Show Gist options
  • Save yao2030/5308214 to your computer and use it in GitHub Desktop.
Save yao2030/5308214 to your computer and use it in GitHub Desktop.
edX problem set 3
def evaluatePoly(poly, x):
result = 0.0
for i in range(len(poly)):
result += poly[i] * x ** i
return result
# poly = [0.0, 0.0, 5.0, 9.3, 7.0]
# x = -13
# print evaluatePoly(poly, x)
def computeDeriv(poly):
result = []
for i in range(1, len(poly)):
result.append(i * poly[i])
return result
#poly = [-13.39, 0.0, 17.5, 3.0, 1.0]
#print computeDeriv(poly)
def computeRoot(poly, x_0, epsilon):
iteration = 0
fx = evaluatePoly(poly, x_0)
while abs(fx) >= epsilon:
fdx = evaluatePoly(computeDeriv(poly), x_0)
x_0 = x_0 - fx / fdx
iteration += 1
fx = evaluatePoly(poly, x_0)
result = [x_0, iteration]
return result
print computeRoot([-13.39, 0.0, 17.5, 3.0, 1.0], 0.1, .0001)
print
print computeRoot([1, 9, 8], -3, 0.01)
print
print computeRoot([1, -1, 1, -1], 2, 0.001)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment