# [Maxima] Using a function as an input to a procedure?

Jaime Villate villate at fe.up.pt
Fri May 2 05:19:39 CDT 2008

```On Fri, 2008-05-02 at 19:25 +1000, Alasdair McAndrew wrote:
> one thing I need to do is to create a small procedure which produces
> the difference between an integral and its trapezoidal approximation;
> such as:
>
> dt(f,a,b):=float(abs(integrate(f(s),s,a,b)-(f(a)+f(b))*(b-a)/2));
>
> But this doesn't work; or at least, when I tried it earlier I got a
> "Too many contexts" error message.  Is there an approved technique for
> writing a procedure which uses functions as inputs?

I don't know if there is an approved technique, but this is something I
do in all of the functions in the package dynamics; I tried several
different methods and the one I liked the most was the following:

dt(f,a,b) :=
block
([intg, approx, var, numer: true, float: true],
if length(listofvars(f)) # 1 then
error("fun should depend on one variable")
else
var: listofvars(f),
intg: integrate(f,var[1],a,b),
approx: (ev(f, var[1]=a) + ev(f, var[1]=b))*(b - a)/2,
abs(intg - approx))\$

Example of its use:

(%i16) dt(x^2,3,5);
(%o16) 1.333333333333336
(%i17) f(x):= 3*x-2\$
(%i18) dt(f(u),3,5);
(%o18) 0.0

I hope this helps.
Jaime

```