Skip to main content
2 of 2
Routine cleanup
m_goldberg
  • 108.6k
  • 16
  • 107
  • 263

Overloading a function to pass in an expression rather that the name of a function

This is an example of procedural programming borrowed from Paul Wellin's book. It's a simple implementation of the Newton-Rhapson method.

I overloaded the findRoot function to accommodate different kinds of arguments. It works fine in the following first case:

findRoot[fun_Symbol, {var_, init_}, ϵ_] := Module[{xi = init}, While[Abs[fun[xi]] > ϵ, xi = N[xi - fun[xi]/fun'[xi]]]; {var -> xi}] f[x_] := x^2 - 2; findRoot[f,{x,2},.0001] 
{x-> 1.41422} 

But when I overload it to accommodate expressions, like the following for example, it doesn't evaluate.

findRoot[expr_== val_, {var_, init_}, ϵ_] := Module[{xi = init, fun = Function[fvar,expr - val]}, While[Abs[fun[xi]] > ϵ, xi = N[xi - fun[xi]/fun'[xi]]]; {var -> xi}] findRoot[x^2 - 2 == 0, {x, 2.0}, 0.0001] 
{x - >2.} 

How do I make Mathematica evaluate it numerically all the way through?