       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:= 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= (-a + x)*Cos[a] + Sin[a]

Out= x

Out= a^2 + 2*a*(-a + x)

Out= 0

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

Out= x

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

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

Out= 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