Re: How to ...?
- To: mathgroup at smc.vnet.net
- Subject: [mg36334] Re: [mg36309] How to ...?
- From: BobHanlon at aol.com
- Date: Mon, 2 Sep 2002 04:08:42 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
In a message dated 8/31/02 1:58:36 AM, berlusconi_pagliusi at fis.unical.it writes: > I'd like to use Mathematica 4.0 to write a function having different > expressions in different domain's intervals. > Let's say: > > F[x_]= x^2 if 0<x<6 > x+1 if x>=6 > > I know It's a stupid syntax problem, but I really do not know how/where to > search the solution on the Mathematica Book > Just for grins here are several methods: f1[x_/;x<=0] := 0 ; f1[x_/;0<x<6] := x^2 ; f1[x_/;x>=6] := x+1; f2[x_] := x^2*UnitStep[x]+(x+1-x^2)*UnitStep[x-6]; f3[x_] := Which[ x<=0, 0, 0<x<6, x^2, x>=6, x+1]; f4[x_] := If[0<x<6,x^2, If[x>=6, x+1,0]]; f5[x_] := Switch[x, _?(#<=0&), 0, _?(0<#<6&), x^2, _?(#>=6&), x+1 ] f6[x_?NumericQ] := {0,x^2,x+1}[[Position[ {x<=0,0<x<6,x>=6}, True][[1,1]]]]; Needs["Calculus`Integration`"]; (* needed for definition of Boole *) f7a[x_?NumericQ] := Evaluate[ (Boole /@ {0<x<6,x>=6}). {x^2,x+1}]; Off[Part::pspec]; f7b[x_?NumericQ] := Evaluate[ {0,x^2,x+1}[[1+Tr[Boole /@ {x>0, x>=6}]]]]; f8[x_?NumericQ] := Cases[ {{x<=0, 0}, {0<x<6, x^2}, {x>=6, x+1}}, {True, z_} :>z][[1]]; f9[x_?NumericQ] := DeleteCases[ {{x<=0, 0}, {0<x<6, x^2}, {x>=6, x+1}}, {False, z_}][[1,2]]; f10[x_?NumericQ] := Select[ {{x<=0, 0}, {0<x<6, x^2}, {x>=6, x+1}}, First[#]&][[1,2]]; f11[x_?NumericQ] := Last[Sort[ {{x<=0, 0}, {0<x<6, x^2}, {x>=6, x+1}}]][[2]]; f12[x_?NumericQ] := Module[{n=1}, While[{x<6,x<0, False}[[n]], n++]; {x+1,x^2,0}[[n]]]; Generating some test points: ts = {Random[Real,{-5,0}],0, Random[Real,{0,6}],6,Random[Real,{6,15}]}; Checking the different representations Equal[(# /@ pts)& /@ {f1,f2,f3,f4,f5,f6,f7a,f7b,f8,f9,f10,f11,f12}] True To pick a favorite, look at how the different definitions behave. Of the definitions that evaluate with symbolic input, only f2 and f4 simplify with assumptions . For example, FullSimplify[#[x]& /@ {f2,f4}, 1<x<3] f2 through f5 respond immediately to differentiation #'[x]& /@ {f2,f3,f4,f5} // Simplify //ColumnForm Only f2 responds immediately to integration Integrate[f2[x],x]//Simplify Consequently, f2 (UnitStep) appears to be the most versatile. Bob Hanlon Chantilly, VA USA