I am writing a code which solve nonlinear algebraic systems via Newton-Raphson algorithm. I want to make a Newton Module with another file and use the Module in my test file, but i didn't achieve it. Because, If the method is not converged, I break the code and return "not converged". Hence, iteration is not continuing and my code is not working properly. Here is my code:
F[y1_,y2_] = {
((y1 - 11)^2 / 64) - ((y2-7)^2/100) -1,
(y1-3)^2 + (y2-1)^2 -400
}; (*Define nonlinear algebraic system vector *)
J[y1_,y2_] = Outer[D,F[y1,y2],{y1,y2}]; (* Find symbolic jacobian *)
{y10,y20}= {20,-4}; (* Initial values for newton iterations *)
Tol = 10^-12;
counter = 0; (*How many newton iterations*)
DeltaY = {0.1,0.1};
MaxIter = 50;
list = Table[{0,0},{i,1,MaxIter}];
(* Begin loop for newton iterations *)
i=1;
While[Norm[ DeltaY, 2] > Tol,
Result = Solve[J[y10,y20].{{dy1},{dy2}}==-F[y10,y20],{dy1,dy2}] //N //Flatten ; (*Solve linear system for Delta y *)
DeltaY = {dy1,dy2}/.Result;
{y10,y20} = {y10,y20} + DeltaY; (*Find new Y values with computed delta y solutions *)
list[[i]] = {y10,y20}; (* Append new computed Y elements into list array *)
Print[list[[i]]," and error:",DeltaY]
Print[Norm[ DeltaY, Infinity]]
If[i>MaxIter,Print["Not converged"] Return[{0,0}];]
counter++
i++;
] //AbsoluteTiming
How can I make n dimensional newton iteration module without breaking code. Also how to return a value with a module.
Note: I will use my newton module for some implicit numerical schemes.
Best regards.
Jac[f_, x_] := Outer[D, f, x];
– drxy Feb 06 '15 at 07:51Function,Jacobian,Max Iteration, Error Tolerance, Dimension. Our module will seems like NewtonMethod[Function,Jacobian,Max Iteration, Error Tolerance, Dimension] = Solution vector or false
– drxy Feb 06 '15 at 08:29Module, or something else? Also, are you certain thatFindRootwill not meet your needs? – bbgodfrey Feb 06 '15 at 11:30Briefly, I want to write an implicit Runge-Kutta package with Mathematica like this matlab script https://bitbucket.org/drreynolds/rklab. If I achieve this, I can publish a paper or book to help people about numerical computations on implicit methods via Mathematica.
Thanks in advance.
– drxy Feb 06 '15 at 11:52FindRoot? – Michael E2 Feb 06 '15 at 13:47FindRootdoes everything you mention you want to do in the question. You can useCheckto see if it complains about convergence. There are also the optionsEvaluationMonitorandStepMonitor, from which you canThrowexceptions.FindRootdoes do some other things automatically or mysteriously, like check step size, so I can understand if you want to write your own. ) – Michael E2 Feb 06 '15 at 14:14