1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2004
Posts
88
Rep Power
14

quick mean-finding 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?
2. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2004
Posts
394
Rep Power
55
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
3. 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```
4. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2004
Posts
88
Rep Power
14
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 ?
5. No Profile Picture
Contributing User
Devshed Intermediate (1500 - 1999 posts)

Join Date
Feb 2004
Location
London, England
Posts
1,585
Rep Power
1377
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
6. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Nov 2004
Posts
88
Rep Power
14
Oh, I see, but why not use i to represent the imaginary number, as it is represented normal algebra?
7. 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