MS-C1650 - Numeerinen analyysi
Lecture 1: Solving Equations

Harri Hakula, 2019

Bisection Method

Clear@BisectionMethod
BisectionMethod::signs="`1` and `2` have same signs?";
BisectionMethod[fun_,{a0_?NumericQ,b0_?NumericQ},delta_?NumericQ]:=Block[{err,c,a=a0,b=b0,fa,fb,fc,conv={}},
err={};
fa=fun[a];
fb=fun[b];
While[Abs[b-a]>2delta,
AppendTo[err,Abs[b-a]];
c=Mean[{a,b}];
AppendTo[conv,c];
fc=fun[c];
If[Sign[fc]≠Sign[fb],
a=c;
fa=fc,
b=c;
fb=fc
]
];
{c,conv}
]/;Sign[fun[a0]]≠Sign[fun[b0]];
BisectionMethod[fun_,{a_?NumericQ,b_?NumericQ},delta_?NumericQ]:=Message[BisectionMethod::signs,fun[a],fun[b]]/;Sign[fun[a]]==Sign[fun[b]];

Example: f(x) = (5-x)*Exp[x]-5

Plot[(5-x)*Exp[x]-5,{x,-2,2},Frame->True,ImageSize->Large]

{res,evx}=BisectionMethod[Function[x,(5-x)*Exp[x]-5],{-2.0,2.0},.01]

ek=Abs[Rest@evx]
data=Transpose[{Most[ek],Rest[ek]}]

ListLogLogPlot[data,Joined->True,PlotMarkers->Automatic,ImageSize->Large]

Last@CoefficientList[Normal[LinearModelFit[Map[Log,data,{2}],{1,x},x]],x]

Bisection Method: f(x) = (x^2)-2

{res,evx}=BisectionMethod[Function[x,x^2-2],{0.0,2.0},.0000001]

ek=Abs[Sqrt[2]-evx]
data=Transpose[{Most[ek],Rest[ek]}]

ListLogLogPlot[data,Joined->True,PlotMarkers->Automatic,ImageSize->Large]

Last@CoefficientList[Normal[LinearModelFit[Map[Log,data,{2}],{1,x},x]],x]

Newton’s Method

Example: f(x) = (5-x)*Exp[x]-5

fun=(5-x)Exp[x]-5

{res,{evx}}=Reap[FindRoot[fun==0,{x,3},EvaluationMonitor:>Sow[x]]]

ek=Abs[(x/.res)-evx]

data=Transpose[{Most[ek],Rest[ek]}]

ListLogLogPlot[data,Joined->True,PlotMarkers->Automatic,ImageSize->Large]

Last@CoefficientList[Normal[LinearModelFit[Map[Log,Most@data,{2}],{1,x},x]],x]

Newton’s Method

Example: f(x) = (x^2)

fun=x^2

{res,{evx}}=Reap[FindRoot[fun==0,{x,3},EvaluationMonitor:>Sow[x]]]

ek=Abs[evx]

data=Transpose[{Most[ek],Rest[ek]}]

ListLogLogPlot[data,Joined->True,PlotMarkers->Automatic,ImageSize->Large]

Last@CoefficientList[Normal[LinearModelFit[Map[Log,data,{2}],{1,x},x]],x]

Secant Method

Example: f(x) = (5-x)*Exp[x]-5

fun=(5-x)Exp[x]-5

{res,{evx}}=Reap[FindRoot[fun==0,{x,2,3},Method->"Secant",EvaluationMonitor:>Sow[x]]]

ek=Abs[(x/.res)-evx][[2;;;;2]]

data=Transpose[{Most[ek],Rest[ek]}]

ListLogLogPlot[data,Joined->True,PlotMarkers->Automatic,ImageSize->Large]

Last@CoefficientList[Normal[LinearModelFit[Map[Log,Most@data,{2}],{1,x},x]],x]

Secant Method

Example: f(x) = (x^2)

fun=x^2

{res,{evx}}=Reap[FindRoot[fun==0,{x,2,3},Method->"Secant",EvaluationMonitor:>Sow[x]]]

ek=Abs[evx][[2;;;;2]]

data=Transpose[{Most[ek],Rest[ek]}]

ListLogLogPlot[data,Joined->True,PlotMarkers->Automatic,ImageSize->Large]

Last@CoefficientList[Normal[LinearModelFit[Map[Log,data,{2}],{1,x},x]],x]