4

I'm writing a program in python that will solve for zeros using newtons method. I finished writing the rough version of it, then realized a couple different things and was wondering if I need to impement/change this. (knowledge of the subject may help)

def main():

   dir(sympy)

   print ("NEWTONS METHOD")
   print ("Write your expression in terms of 'x' ") 

   e = sympy.sympify(raw_input("input expression here: "))  
   f = sympy.Symbol('x')


   func1 = e
   func1d = sympy.diff(e,f) 


   print ("the dirivative of your function = "), func1d

   x = input("number to substitude for x: ")


   func1sub = func1.subs({'x':x})
   func1dsub = func1d.subs({'x':x})
   n = x - float(func1sub/func1dsub)



   while n != x:
      func1sub = func1.subs({'x':x})
      func1dsub = func1d.subs({'x':x})
      n = x - float(func1sub/func1dsub)
      print n



main()

1) Well first I was wondering since the values of n and x may not always be exactly the same I would have to round using the round function.

2) After looking at this I feel that my while loop is not solving for what it should be solving, it should be solving for what is the x that you can plug it into x in the function and the output will be x. Could I do this by appending the values to a array then seeing where their are multiples instances of one number?

Pablo
  • 8,408
  • 2
  • 36
  • 29
Shantanu
  • 484
  • 5
  • 14

2 Answers2

2

Q1: I agree.

Q2: x = n near the top of loop. You want to move on.

yosukesabai
  • 5,785
  • 4
  • 23
  • 39
  • but im not seeing if x = n im seeing at what number n is going to constantly be equal to n after going through the equation – Shantanu Nov 22 '11 at 16:12
  • The method is recursive. you use x1 to calculate x2, then use x2 to calculate x4 and so on until you got satisified. in your notation you calclated n based on x. this is like you got x2 (n) from x1(x). Now you want repeat the same deal using this time x2 on the right hand side of formula. Hence you need to move over n (i.e. x2) to x (now x has x2, so that you are going to get x3 as n) – yosukesabai Nov 22 '11 at 18:04
2

First of all, the value of x isn't changing in your while loop.

Second, the termination criterion should be that the "current" estimation vs the "previous" one should be "sufficiently close", that is.. you should use something like:

while abs(current - previous) > tolerance:
Pablo
  • 8,408
  • 2
  • 36
  • 29
  • I agree. It would also be good practice to add checks for division by zero (for the derivative term) and for divergence (e.g. check whether the estimate remains within certain bounds). – dimatura Nov 22 '11 at 06:01