MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Function Programming Problems

  • To: mathgroup at smc.vnet.net
  • Subject: [mg90818] Re: Function Programming Problems
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Fri, 25 Jul 2008 06:15:22 -0400 (EDT)
  • Organization: The Open University, Milton Keynes, UK
  • References: <g69fqt$ie1$1@smc.vnet.net>

davey79 at gmail.com wrote:

> A colleague and myself are working on some Mathematica labs for
> Calculus using Mathematica 6.0 and I can't seem to find any
> information or examples that explain defining functions and using
> functions as arguments.
> 
> I want to define a LinearApproximation command that preferably would
> take two arguments and return the linear approximation.  Ideally,
> 
> LinearApproximation[function_,a_] would have
> LinearApproximation[Sin[x],0] give "x" as the output.
> 
> So far I have:
> LinearApproximation[function_, a_, x_] := function[a] +
> function'[a]*(x - a)
> 
> which works mostly nicely, except it only works with
> LinearApproximation[Sin,0,x].
> 
> Does anyone know how I would fix this to allow Sin[x] as input (or
> even x^2, etc)?  Getting rid of the third argument "x" would be nice,
> but not necessary.

One possible way is as follow.

First, we prevent the evaluation of the first argument of our function 
so it is written/replaced in the body as it is.

Both definitions have an optional third argument that holds the name of 
the independent variable, assuming that the default name is "x" (so the 
function also works when called with only two arguments).

The first definition handles the case when the function is provided in 
the form "f[x]". The second definition handles the case when the 
function is provided just as "f" (without the independent variable).


     In[1]:= SetAttributes[linApp, HoldFirst]

             linApp[fun_, a_, var_: x] := (fun /. var -> a) +
               (D[fun, var] /. var -> a)*(var - a)

             linApp[fun_Symbol, a_, var_: x] := (fun[var] /. var -> a) +
               (D[fun[var], var] /. var -> a)*(var - a)

             linApp[Sin[x], a]
             linApp[Sin[x], 0]
             linApp[x^2, a]
             linApp[x^2, 0]
             linApp[Sin, a]
             linApp[Sin, 0]
             linApp[Sin[y], a, y]
             linApp[Sin, a, z]
             linApp[t^2, b, t]

     Out[4]= (-a + x)*Cos[a] + Sin[a]

     Out[5]= x

     Out[6]= a^2 + 2*a*(-a + x)

     Out[7]= 0

     Out[8]= (-a + x)*Cos[a] + Sin[a]

     Out[9]= x

     Out[10]= (-a + y)*Cos[a] + Sin[a]

     Out[11]= (-a + z)*Cos[a] + Sin[a]

     Out[12]= b^2 + 2*b*(-b + t)


Regards,
-- Jean-Marc


  • Prev by Date: Re: Function Programming Problems
  • Next by Date: Re: Can't Simplify logical expression
  • Previous by thread: Re: Function Programming Problems
  • Next by thread: Reading Directive Values