Advertisement
Guest User

Python Newton's Method

a guest
Jul 22nd, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. #a - [f(a)/f'(a)] = f(b)
  2. #polynomial = input("Input polynomials in the form ax^n + bx^n-1 + ...")
  3. polyCoef = []
  4. deriv_polyCoef = []
  5. polyValue = []
  6. deriv_polyValue = []
  7. deriv_polyCoef = []
  8. i = 0
  9. j = 0
  10.  
  11. def main():
  12. polyLength = int(input("How many terms are in your polynomial? (including zero terms) "))
  13. for i in range(polyLength):
  14. coef = int(input(str(i + 1) + " coefficient "))
  15. polyCoef.append(coef)
  16. print(polyCoef)
  17. print("Is this your polynomial?")
  18. for j in range(polyLength):
  19. print(str(polyCoef[j]) + "x^" + str(polyLength - j - 1))
  20. polyContinue = input("If it is not, type 'n' to re-input coefficients. Otherwise, type anything else to continue ")
  21. if polyContinue != "n":
  22. for k in range(polyLength):
  23. deriv_power = int(polyLength - k - 1) #New power after differentiation
  24. deriv_coef = int(polyCoef[k]) * deriv_power #New coefficient after differentiation
  25. deriv_polyCoef.append(deriv_coef)
  26. print(deriv_polyCoef)
  27. print("This is your new polynomial, ")
  28. for l in range(polyLength):
  29. print(str(deriv_polyCoef[l]) + "x^" + str(int(polyLength - l - 2)))
  30. else:
  31. polyCoef.clear()
  32. main()
  33.  
  34. def newtonMthd():
  35. newtonIteration = int(input("Type your starting point.")) #this is the starting point
  36. repeat = int(input("How many iterations would you like?"))
  37. for iteration in range(repeat):
  38. print("This is your starting point " + str(newtonIteration))
  39. for m in range(len(polyCoef)):
  40. polyInput = polyCoef[m] * (int(newtonIteration) ** (len(polyCoef) - m - 1)) #plugs in the starting point into the given polynomial
  41. polyValue.append(polyInput) #this is f(x1)
  42. for n in range(len(polyCoef) - 1):
  43. deriv_polyInput = int(deriv_polyCoef[n]) * (int(newtonIteration) ** (len(polyCoef) - n - 2)) #plugs in the starting point into the derivative of f(x)
  44. deriv_polyValue.append(deriv_polyInput) #this is f'(x1)
  45. newtonIteration = int(newtonIteration) - ((int(sum(polyValue)))/int((sum(deriv_polyValue)))) #this is the generalized form of newton's method to solve for x_2
  46. print("Iteration = " + str(newtonIteration))
  47. main()
  48. newtonMthd()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement