Re: Problem with the 'if' command
- To: mathgroup at smc.vnet.net
- Subject: [mg96604] Re: [mg96578] Problem with the 'if' command
- From: Bob Hanlon <hanlonr at cox.net>
- Date: Tue, 17 Feb 2009 06:24:41 -0500 (EST)
- Reply-to: hanlonr at cox.net
You are testing the wrong condition, also you must ensure that the list is sorted and that the input is a list.
newMedian[list_List] := Module[
{len = Length[list], sortedList = Sort[list]},
If[IntegerQ[len/2],
(sortedList[[(len/2) + 1]] + sortedList[[len/2]])/2,
sortedList[[(len + 1)/2]]]]
newMedian2[list_List] := Module[
{len = Length[list], sortedList = Sort[list]},
If[Mod[len, 2] == 0,
(sortedList[[(len/2) + 1]] + sortedList[[len/2]])/2,
sortedList[[(len + 1)/2]]]]
newMedian3[list_List] := Module[
{len = Length[list], sortedList = Sort[list]},
If[EvenQ[len],
(sortedList[[(len/2) + 1]] + sortedList[[len/2]])/2,
sortedList[[(len + 1)/2]]]]
a = Table[RandomInteger[{0, 1000}, {RandomInteger[{10, 20}]}],
{10000}];
And @@ (newMedian[#] == newMedian2[#] == newMedian3[#] == Median[#] & /@ a)
True
Bob Hanlon
---- mathandpi <mathandpi at yahoo.com> 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,
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,
newMedian[{1, 2, 3, 4}] returns:
Part::pspec: Part specification 5/2 is neither an integer nor a list of integers.
BUT
list={1,2,3,4};
1/2*(list[[(Length[list]/2) + 1]] + list[[(Length[list])/2]])
returns 5/2, as expected so that code is right.
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.
What's going on here?
Thanks