[Tutor] newton's method for system of nonlinear equations

A.T.Hofkamp a.t.hofkamp at tue.nl
Fri Jun 26 14:08:22 CEST 2009


kgotlelelok at galmail.co.za wrote:
> Hi,
> I am trying to write a program in python that solves a system of nonlinear
> equations using newton's method. I don't know what I am doing wrong.
 > Please help

In general, it helps for both you and us if you show what happens when you run 
the program, and how that is not according to your expectations.

In this case, you just say "I don't know what I am doing wrong".
We can look at the code and see what will happen when one executes it, but we 
don't know how that is wrong for you.

> from scipy import*

Many readers here (including self) don't know much about numerical stuff, so 
if that's your problem, maybe posting at a scipy related list may be more useful.

> x = array([0.0,0.0,0.0])
> n=len(x)
> tol= 0.00001
> N=30
> 
> k=1
> while k <= N:
>     def f(x):
>         f= zeros((len(x)),float)
>         f[0][k]= x[0][k]**2 + x[1][k]-37
>         f[1][k]=x[0][k]- x[1][k]**2- 5
>         f[2][k]= x[0][k] + x[1][k]+ x[2][k]- 3
>         return f[k]
>         def J(x):
>             J= zeros((n,n),float)
>             for i in range(n):
>                 ei=zeros(n,float)
>                 ei[i]=1.0
>                 J[:i]=(f(x[k]+tol*ei)-f(x[k]))/tol
>                 return J
> 
>         y[k] = -(J.I)*f[k]
>         x[k+1]=x[k]+y[k]

You have a while loop, and inside the loop you define a function called 'f'.
Can you explain what you think should happen here?

> 
> if sqrt(dot(f0,f0)/len(x)) < tol: print x

f0 is never defined above, so you will get an 'undefined identifier f0' error 
here.
What is f0 supposed to be?
(if you intended to call 'f' here, type 'f(0)' instead of 'f0')
(Calling f probably makes sense only if the 'if' statement is inside the 
'while' loop. See also below.)

> else:
>     k=k+1

The 'if' statement is after the 'while' loop. Incrementing k here does not 
make much sense here.
Maybe you meant the 'if' inside the 'while'?
If so, indent the statement accordingly (same amount as the "def f(x):" line).


Albert



More information about the Tutor mailing list