Re: Problem with the 'if' command
- To: mathgroup at smc.vnet.net
- Subject: [mg96625] Re: Problem with the 'if' command
- From: Albert Retey <awnl at gmx-topmail.de>
- Date: Tue, 17 Feb 2009 06:28:33 -0500 (EST)
- References: <gncme2$fid$1@smc.vnet.net>
mathandpi wrote:
> Hi everyone,
> I'm a new Mathematica user so I may be missing something fairly obvious, but I'm having trouble with the 'if' command.
> I'm writing a function that is supposed to return the median of a list (I know such a function already exists, but I need to create one myself).
>
> What I have is:
>
> newMedian[list_] :=
> If[Length[list]/2 == 0,
^^^^^^^^^^^^^^^^^^^
Could it be you want something like: Mod[Length[list],2]==0 or even
better EvenQ[Length[list]] here? Length[list]/2 == 0 will always return
false except when Length[list] == 0, or list === {} ...
> 1/2*(list[[(Length[list]/2) + 1]] + list[[(Length[list])/2]])
> , list[[(Length[list] + 1)/2]]]
>
> if the list has an off number of members (condition is false), it evaluates as expected. If it's even, however,
>
> It seems likes its actually evaluating the false part of the code (trying to find the 5/2'ith element in a list), even though the condition is true.
>
hth,
albert