Re: Putting a Test or Condition on the Right-Hand Side of a Function
- To: mathgroup at smc.vnet.net
- Subject: [mg127474] Re: Putting a Test or Condition on the Right-Hand Side of a Function
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Fri, 27 Jul 2012 04:59:36 -0400 (EDT)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- Delivered-to: mathgroup-newout@smc.vnet.net
- Delivered-to: mathgroup-newsend@smc.vnet.net
On 7/26/12 at 3:35 AM, gregory.lypny at videotron.ca (Gregory Lypny) wrote: >I have a simple function that displays the integer part of a real >number if the fraction part is less than a millionth. >dropDecimal[x_] := If[FractionalPart[x] < .000001, IntegerPart[x], >x] >In trying to learn more about functional programming, I was wondering >whether there is a way to put the condition or test on the right-hand >side of the function. You could do this as follows: In[6]:= dropDecimal[x_] := IntegerPart[x] /; FractionalPart[x] < .000001 dropDecimal[x_] := x /; FractionalPart[x] > .000001 In[8]:= dropDecimal[N[56 + 10^(-6)]] Out[8]= 56 In[9]:= dropDecimal[N[56 + 10^(-4)]] Out[9]= 56.0001 But I think this would be a much better definition for this function: In[10]:= Clear[dropDecimal]; dropDecimal[x_] := Round[x, .000001] In[12]:= dropDecimal[N[56 + 10^(-6)]] Out[12]= 56. In[13]:= dropDecimal[N[56 + 10^(-4)]] Out[13]= 56.0001 However, this isn't quite the same since the output isn't an exact value and the use of Round means something just slightly less than the threshold gets rounded up rather than truncated.