Calculating median - javascript -
i've been trying calculate median still i've got mathematical issues guess couldn't correct median value , couldn't figure out why. here's code;
class statscollector { constructor() { this.inputnumber = 0; this.average = 0; this.timeout = 19000; this.frequencies = new map(); (let of array(this.timeout).keys()) { this.frequencies.set(i, 0); } } pushvalue(responsetimems) { let req = responsetimems; if (req > this.timeout) { req = this.timeout; } this.average = (this.average * this.inputnumber + req) / (this.inputnumber + 1); console.log(responsetimems / 1000) let groupindex = math.floor(responsetimems / 1000); this.frequencies.set(groupindex, this.frequencies.get(groupindex) + 1); this.inputnumber += 1; } getmedian() { let medianelement = 0; if (this.inputnumber <= 0) { return 0; } if (this.inputnumber == 1) { return this.average } if (this.inputnumber == 2) { return this.average } if (this.inputnumber > 2) { medianelement = this.inputnumber / 2; } let mincumulativefreq = 0; let maxcumulativefreq = 0; let cumulativefreq = 0; let freqgroup = 0; (let of array(20).keys()) { if (medianelement <= cumulativefreq + this.frequencies.get(i)) { mincumulativefreq = cumulativefreq; maxcumulativefreq = cumulativefreq + this.frequencies.get(i); freqgroup = i; break; } cumulativefreq += this.frequencies.get(i); } return (((medianelement - mincumulativefreq) / (maxcumulativefreq - mincumulativefreq)) + (freqgroup)) * 1000; } getaverage() { return this.average; } }
here's snapshot of results when enter values of
342,654,987,1093,2234,6243,7087,20123
the correct result should be;
median: 1663.5
change median method this:
function median(values){ values.sort(function(a,b){ return a-b; }); if(values.length ===0) return 0 var half = math.floor(values.length / 2); if (values.length % 2) return values[half]; else return (values[half - 1] + values[half]) / 2.0; }
Comments
Post a Comment