The Math
While doing some math revision within my free time, I decided to create a simple Go program to calculate the average concepts of Mean and Median.
The definition of mean says that you should sum up all the numbers and divide them by how many numbers you did the sum.
For instance, suppose that the numbers are 2, 3 and 7. Adding all these numbers must give the result of 12.
Now, we just need to divide 12 by 3, because 3 is the total of the number we did sum! Resulting in 4.
On the other hand, the definition of median is a little bit more “complicated”!
It says that a median number is a number in the middle of an ordered list of numbers. To find that middle number, first, we should order the numbers then, we need to know if the quantity of numbers in this list is either odd or even.
The easiest of both is the odd case, because in that case, you go straight to the middle number, example:
In a list of numbers: 1, 3, 6, 10, 12, 15, 17 (already in order) the middle number will be 10!
But, in the case of an even list of number, we need to do some additional steps.
First, we need to take the two middle numbers from the list. After, we sum both of them and divide by 2, as follow:
Numbers: 1, 2, 4, 6 (already in order), the middle number will be the result of (2 + 4) / 2, which is 3!
The Go
The Go code is pretty straightforward!
If you are thirsty to see the code, just access my git repository about how to calculate mean and median with Go.
Or… by the Go Playground!
We have two functions that deal with the calculation of mean and median (as their name says) and, an extra function to validate if the list of numbers is either odd or even.
The function CalcMean() simply loop over all the numbers, summing it up, and then divides this value by the total of numbers present in the list.
func (mm *MeanMedian) CalcMean() float64 {
total := 0.0
for _, v := range mm.numbers {
total += v
}
// IMPORTANT: return was rounded!
return math.Round(total / float64(len(mm.numbers)))
}
Now, in the CalcMedian() function, we have a couple of interesting things happening:
- First, we sort the numbers, using sort.Float64s().
- Then, we check if the list of number is odd or even by calling the function isOdd().
- If it’s an odd list, we take the middle number.
- If it’s an even list, we add both of the middle numbers, then divide it by 2.
func (mm *MeanMedian) CalcMedian(n ...float64) float64 {
sort.Float64s(mm.numbers) // sort the numbers
mNumber := len(mm.numbers) / 2
if mm.IsOdd() {
return mm.numbers[mNumber]
}
return (mm.numbers[mNumber-1] + mm.numbers[mNumber]) / 2
}
What about these functions GetMinValue(), GetMaxValue() and CalcRangeValues() ?
Good news!!! – Consider it as a bonus! 🙂
Basically, they just return the first element in the list (GetMinValue), the last element in the collection (GetMaxValue) and calculate the range value (CalcRangeValues), i.e. the difference between the last and the first elements.