Piecewise functions




I have includied what I have accomplished so far.  I will send an example usage file next.

Rich



kill(all);

pwintegrate(expr,x):=
block
(
    [__i, __l],
    if matrixp(expr) and length(expr[1]) = 11 and expr[1,1] = "If" then
    (
        __l:[],
        if length(expr[1]) = 11 then
        (
            for __i: 1 thru length(expr) do __l:endcons([expr[__i,5],expr[__i,7], __rsum(expr[__i,11], x)],__l),
            pw(__l,x)
        )
    )
    else
        __rsum(expr,x)
)$

pwdefint(expr,x,[v]):=
block
(
    [__i, __s],
    if matrixp(expr) and length(expr[1]) = 11 and expr[1,1] =  "If" then
        if length(v)=0 then
            pwintegrate(expr,x)
        elseif length(v) = 2 then
        (
            __s:0,
            for __i: 1 thru length(expr) do __s:__s+__rsum(expr[__i,11], x,max(v[1],expr[__i,5]),min(v[2],expr[__i,7])),
            __s
        )
        else
            error("Wrong number of arguments to integrate")
    else
    (
        if length(v)=0 then
            __rsum(expr,x)
        elseif length(v) = 2 then
            __rsum(expr,x,v[1],v[2])
        else
           error("Wrong number of arguments to integrate")
    )
)$

pwdiff(expr,x,[v]):=
block
(
    [__i, __l, __n],
    if matrixp(expr) and length(expr[1]) = 11 and expr[1,1] = "If" then
    (
        if length(v)=0 then __n : 1 elseif length(v)>0 then __n : v[1],
        __l:[],
        for __i: 1 thru length(expr) do __l:endcons([expr[__i,5],expr[__i,7], __diff(expr[__i,11], x,__n)],__l),
        pw(__l,x)
    )
    else
    (
        if length(v)=0 then __n : 1 elseif length(v)=1 then __n : v[1],
            __diff(expr,x,__n)
    )
)$

pw(L,x):=
block
(
    [__M,__k],
    if listp(L[1]) then
    (
        __M:matrix(["If", x,"in","[",L[1][1], ",", L[1][2],"]",'pw(x),"=",L[1][3]]),
        for __k: 2 thru length(L) do (if listp(L[__k]) then if length(L[__k])=3 then
            __M:addrow(__M,["If", x,"in","[",L[__k][1], "," ,L[__k][2],"]",'pw(x),"=", L[__k][3]]))
    )
    else
    (
        __M:matrix(["If",x,"in","[",L[1], ",", L[3],"]",'pw(x),"=",L[2]]),
        for __k:2 thru length(L)-3 step 2 do
        (
            __M:addrow(__M,["If",x,"in","[",L[1+__k],",",L[3+__k],"]",'pw(x),"=",L[2+__k]])
        )
    ),
__M
)$

pwsumify(expr):=block
(
    [__i,__retval],
    if matrixp(expr) and length(expr[1]) = 11 and expr[1,1] =  "If" then
    (
           retval:sum(expr[i,11]*(unit_step(expr[i,2]-expr[i,5])-unit_step(expr[i,2]-expr[i,7])), i, 1, length(expr))
    )
    else
        retval:0
)$

compile(pw,pwdefint,pwdiff,pwintegrate,pwsumify);

:lisp (setf (symbol-function '$diff) (symbol-function '$pwdiff));

:lisp (setf (symbol-function '$integrate) (symbol-function '$pwdefint));

compfile("c:/pw.lisp", functions);

define(g(x), pwsumify(pw([-10,-x^2,0,(50-50*cos(%pi*x/10)),10],x)));

plot2d([g(x)], [x,-9.9999,9.9999], [plot_format, gnuplot])$

Rich