[metapost] Function defined by a sum

Mojca Miklavec mojca.miklavec.lists at gmail.com
Fri Nov 2 13:16:26 CET 2007


On 11/2/07, Nicolas FRANCOIS wrote:
> Le Fri, 2 Nov 2007 11:21:19 +0100 "Mojca Miklavec"
> <mojca.miklavec.lists at gmail.com> a écrit :
>
> > There is no "sum" (unless you define one), but oyu can use "for" loop:
> >
> > vardef sin(expr xx) = sind(xx*180/3.14) enddef;
> >
> > vardef f(expr xx,n) =
> >    save sum;
> >    sum:=0;
> >    for i=1 upto n:
> >       sum := sum+sin(i*(xx))/i;
> >    endfor;
> >
> >    sum
> > enddef;
> >
> > beginfig(1);
> >    path p;
> >    p := (0,0)
> >    for j=1 upto 700:
> >       --(j/100,f(j/100,3))
> >    endfor;
> >    draw p scaled 1cm;
> > endfig;
> > end.
>
> Thanks. Someone on another list gave me something more "TeXish" :
>
> vardef sum_sin(expr x,n)=
>   0
>   for k:=1 upto n:
>     + sin(k*x)/x
>     endfor
> enddef;

Sure, that's a more elegant solution. It gets expanded directly into
    return 0+sin(1*x)/1+sin(2*x)/2+...+sin(n*x)/n (whatever n is)
while my example was doing
    sum:=0;
    sum:=sum+sin(1*x)/1;
    sum:=sum+sin(2*x)/2;
    ...
    return sum

> I thought something like this could work. But I don't know exactly why.
> Is this something like "token replacement", like in TeX ? Where can this
> be explained in the Metapost documentation ?

It's described a bit in "Loops" (section 10, page 85 in the manual for
version 1.000).

It's exactly the same trick that is used afterwards for drawing the
path. I don't know how to explain it (for is like a macro that appends
the content to what we had before the loop instead of executing some
commands step-by-step - the content is then "evaluated" when the first
";" appears - sorry for the horrible wording, but I really have no
idea how to explain it in any other way. Read the section 1 of mpman
carefully).

Mojca


More information about the metapost mailing list