home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: sci.math.symbolic
- Path: sparky!uunet!cis.ohio-state.edu!zaphod.mps.ohio-state.edu!moe.ksu.ksu.edu!ux1.cso.uiuc.edu!news.cso.uiuc.edu!usenet
- From: Richard J. Gaylord <gaylord@ux1.cso.uiuc.edu>
- Subject: Re: Mathematica: defining functions. HELP!
- References: <l8mkk4INN5ll@halcyon.usc.edu>
- Message-ID: <Bt14s4.MAA@news.cso.uiuc.edu>
- X-Xxdate: Sat, 15 Aug 92 09:41:03 GMT
- Sender: usenet@news.cso.uiuc.edu (Net Noise owner)
- X-Useragent: Nuntius v1.1.1d7
- Organization: University of Illinois
- Date: Sat, 15 Aug 1992 14:40:50 GMT
- Lines: 35
-
- Subject: Re: Mathematica: defining functions. HELP!
- From: Dave Seaman, ags@seaman.cc.purdue.edu
- Date: 14 Aug 92 14:30:59 GMT
- In article <56833@mentor.cc.purdue.edu> Dave Seaman,
- ags@seaman.cc.purdue.edu writes:
- >In article <l8mkk4INN5ll@halcyon.usc.edu> rao@halcyon.usc.edu (Anil Rao)
-
- >writes:
- >> define a function f(x) = x between x = 2 and x = 5
- >> = x^2/2 for x < 2
- >> = 5 x - 20 for x > 5
- >>
- >
- >At least two methods come to mind. One is to qualify the definitions:
- >
- > f[x_] := x /; 2 <= x <= 5
- > f[x_] := x^2/2 /; x < 2
- > f[x_] := 5 x - 20 /; x > 5
- >
- >and another way is to use a one-liner with nested conditionals:
- >
- > f[x_] := If[ x<2, x^2/2, If[ x<=5, x, 5 x - 20]]
- >
-
- ======================================
-
- a one-liner can be written without nesting
-
- f[x_] := Which[x<2, x^2/2, x<= 5, x, True, 5x - 20]
-
- comment: note that in the one-liner it is sufficient to use x<=5 because
- M goes through Which[..] from left to right, while in the rule-based
- method given above, we have to use 2<=x<=5 so that the rules don't have
- overlapping domains because we can't be really sure how M will decide
- what rule to use when.
-