【发布时间】:2016-03-02 23:51:59
【问题描述】:
从以下取自here的Maxima代码开始
/* piecewise function definition */
itvs: [[x<0],[x>=0,x<1], [x>=1]]; /* intervals */
pfun: [ a, x^2+b, c*x ]; /* local functions */
/* piecewise function constructor */
f:0$
for i: 1 thru 3 do f:f+charfun(apply("and",itvs[i]))*pfun[i]$
f;
/* differentiation of piecewise function */
gradef(charfun(dummy),0)$
diff(f,x);
我想让一个函数能够接受itvs和pfun之类的2个参数并返回f之类的分段函数,但是由于符号评估导致的错误,我无法做到这一点.例如,在下面的尝试中,我收到错误“语法不正确:itvs 不是中缀运算符”:
define(pfc(itvs,pfun),(
f:0,
for i: 1 thru length(itvs) do f:f+charfun("and" itvs[i])*pfun[i],
f
));
如何定义这样的函数? 我找到的文档非常简洁,无法帮助我,是否有一些关于这个主题的鲜为人知的文档?
编辑
输入参数的另一种格式可能更简单、更灵活,可以是:
/* piecewise function definition */
pfd: [
[a, x<0],
[x^2+b, x>=0 and x<1],
[c*x, x>=1]
];
使用此参数编写函数构造函数可能更简单。
跟进
如果您实际上不需要分段 函数,因为分段 表达式 就足够了(正如我后来发现的那样——在我的例子中),编写分段表达式构造函数(使用输入参数的替代格式)变得简单:
/* pec=piecewise expression constructor */
/* argument is an array of [expression,interval] couples */
pec(x) := sum(x[i][1]*charfun(x[i][2]), i,1,length(x));
f: pec( [[(1+x)/2, x>=-1 and x<1],[3, x<-1 or x>=1]] )
(f) 3*charfun(x<-1 or x>=1)+((x+1)*charfun(x>=-1 and x<1))/2
【问题讨论】: