Newtons Method in Python

I am writing a program in python that will solve for zeros using the newtons method. I ended up writing a rough version, then I realized a couple of different things, and I was wondering if I need to empirize / 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, at first I was interested, because the values ​​of n and x may not always be the same, I would have to use a round function.

2) Having looked at this, I feel that my while loop does not decide what it should be solved for, it should decide what x , which you can connect to it in x in the function and the output will be x . Can I do this by adding values ​​to the array and then seeing where their multiple instances of the same number are?

+4
source share
2 answers

First of all, the value of x does not change in your while .

Secondly, the termination criterion should be that the "current" rating compared to the "previous" should be "fairly close", that is .. you should use something like:

 while abs(current - previous) > tolerance: 
+2
source

Q1: I agree.

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

+2
source

Source: https://habr.com/ru/post/1382423/


All Articles