MathGroup Archive 1998

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Automatic generation of piecewise functions



William F. Campbell wrote:
>

>   I am trying to generate a single function f[x], which has different
> definitions depending on the values of x (i.e. a piecewise function).
> I proceeded as follows:
>

> Clear[f];
> sampleÚble[f[x_]«i]*x+b[i]/;Evaluate[x>-1&&x<-,{i,2}]
>

> The output returned looked correct:
> {b[1]+a[1] x/;x>&x<b[2]+a[2] x/;x>&x<-
>

> When I looked at the definition for f, it seemed correct as well: ?f
>

> Global `f
>

> f[x_]»1]+a[1] x/;x>&x<
>

> f[x_]»2]+a[2] x/;x>&x<-
>

> But when I attempted to use the definition, f[0.5]
>

> 0.5 a[1]+b[1]/;0.5>&0.5<
>

> whose full form is
> FullForm[f[0.5]]
>

> Condition[Plus[Times[0.5,a[1]],b[1]],
>   And[GreaterEqual[0.5,0],LessEqual[0.5,1]]]
>

> Why doesn't the Condition evaluate?  How can I change the construct used
> in sample above to obtain a working definition for a piecewise
> function?  BTW, If I fail to put Evaluate[] around the condition in the

> definition of sample above, the output is even further from what I
> want, {b[1]+a[1] x/;x>-1&&x<,b[2]+a[2] x/;x>-1&&x<-. --

> Bill Campbell                          Correlation is not cause.

Bill:

Some points.

1) With Set ( Condition must be on left side:

r[x_] x/;x>

l[x_]/;x>x;

{r[.5],l[.5]}

{1.5/;0.5*0,1.5}

With SetDelayed (:Condition can be on either side:

rd[x_] :x/;x>

ld[x_]/;x>:x;

{rd[.5],ld[.5]}

{1.5,1.5}


2) Then there is the matter of evaluating the condition to get the
values of the index i inside it - this you solve by using Evaluate.

Here I combine this with moving the condition to the left AND inside f

ClearAll[f];
Table[f[x_/;Evaluate[i-1<x<-] 
[i]*x,{i,2} ];

{f[.5],f[1.5]}

{0.5 a[1],1.5 a[2]}

If f has two places the condition may have to be outside f and then an
extra
Evaluate is needed

ClearAll[f];
Table[Evaluate[f[x_,y_]/;Evaluate[i-1<x+y<-] 
[ i]*x,{i,2} ];

{f[.5,0],f[1.5,0]}

{0.5 a[1],1.5 a[2]}


However, forcing evaluation may do more than we want; and using
replacement or
With may suit us better (though the former may replace too much and the
latter
may get tangled up with renaming in scoping constructs):

ClearAll[f];
Table[
	Unevaluated[
			f[x_,y_]/;i-1<x+y<-a[ i]*x
	]/.i->j,{j,2}
];  (*Unevaluated puts assignment after replacement*)


{f[.5,0],f[1.5,0]}

{0.5 a[1],1.5 a[2]}

ClearAll[f];
Table[
	With[{i-,
		f[x_,y_]/;i-1<x+y<-a[ i]*x
	],
	{i,2}
];

{f[.5,0],f[1.5,0]}

{0.5 a[1],1.5 a[2]}

--

Allan Hayes
Training and Consulting
Leicester, UK
hay@haystack.demon.co.uk
http://www.haystack.demon.co.uk
voice: +44 (0)116 271 4198
fax: +44 (0)116 271 8642




  • Prev by Date: Re: AngleBracket[] -- serious bug?!
  • Next by Date: Mathematica 3.0: How to change thickness of 3D-curve (ParametricPlot3D)
  • Prev by thread: RE: Automatic generation of piecewise functions
  • Next by thread: shuffling a large set in Mathematica