October 8th, 2005, 11:16 AM

quick meanfinding function
Alright, I've tried to make a really condensed function to determine the mean of a list of data.
I've come up with:
Code:
def mean(self,list_of_data):
if len(list_of_data) < 1:
return 0
summation = 0
for number in range(len(list_of_data)1):
summation += list_of_data[number]
return summation/len(list_of_data)
However, it returns inaccurate answers, such as the mean of 90,95,100 as being 61
Have I overlooked something obvious in my quest to make a compact function?
October 8th, 2005, 01:58 PM

Hi!
To make it more compact, calculate the sum of the list with ... sum()
Code:
>>> l = [1,2,3,4]
>>> mean = sum(l) / float(len(l))
>>> mean
2.5
Regards, mawe
October 8th, 2005, 02:13 PM

Or if you want to keep your idea:
Python Code:
def mean(l):
if len(l) < 1:
return 0
sum = 0
for n in range (0, len(l)):
sum += l[n]
return sum/len(l)
>>>mean([1, 3, 5, 7, 9, 13])
>>>6
Note that this is not entirely correct (38/6), so if you want full precision make sum = 0.0
Python Code:
def mean(l):
if len(l) < 1:
return 0
sum = 0.0
for n in range (0, len(l)):
sum += l[n]
return sum/len(l)
>>>mean([1, 3, 5, 7, 9, 13])
>>>6.333333333
Am I supposed to sign here?
October 8th, 2005, 02:22 PM

much thanks
I forgot about making the result a float too, that would've been another source of error
And just a quick other questions:
why does the cmath.sqrt function return 0j ?
October 8th, 2005, 04:12 PM

Originally Posted by pylon
why does the cmath.sqrt function return 0j ?
0j is how python represents 0 as a complex number. A complex number consists of an optional real part, plus a complex part. The j shows that the number is complex, just like the decimal point in 0.0 shows that the number is floating point. They are all the same number, but represented by different types.
python Code:
>>> complex(0)
0j
>>> complex(1)
(1+0j)
>>>
Dave
October 8th, 2005, 04:39 PM

Oh, I see, but why not use i to represent the imaginary number, as it is represented normal algebra?
October 10th, 2005, 06:14 AM

i and j are both correct but are from different historical roots.
From fading memory  we used i in Maths but used j in my Engineering course.
I guess most programmable complex math is used in an engineering context.
grim