I’ve tried two different approaches to calculating the median, and have realised and solved the issue of alphabetical sorts. However, there still seems to be a problem with calculating the median of an array with an even number of elements.
In this example I have the following function in code_JS
median = function (values){
if(values.length ===0) return 0;
values.sort(function(a,b){
return a-b;
});
var half = Math.floor(values.length / 2);
if (values.length % 2)
return values[half];
return (values[half - 1] + values[half]) / 2.0;
}
Here are some arrays (from console.log)
rtMidSY=187
rtMidSN=378,329,445
rtMidSY0=102,152,441,200,256,216,440,234,392,358,270,506
rtMidMY=135,60,66,85,101,68,80
rtMidMN=36,222,56,86,87,95
rtMidMY0=1611,144,136,149,168,169,144,712,183,148,157,143
Here are the corresponding medians calculated by the function (in the same order as above)
187
378
128135
80
4343.5
74578.5
My previous attempt had a sort function in code_JS
sort = function(array) {
return array.sort((a, b) => (a - b));
}
and then the following auto translated Python steps for the calculation
sort(rtListSY)
rtMidSY = (len(rtListSY)+1)/2-1
if rtMidSY == round(rtMidSY):
results[0][5]=rtListSY[int(rtMidSY)]
else:
results[0][5]=(rtListSY[int(rtMidSY-.5)]+rtListSY[int(rtMidSY+.5)])/2
It also gave huge numbers for arrays with an even number of elements.
Any ideas?