gpt4 book ai didi

javascript - 计算中位数 - javascript

转载 作者:可可西里 更新时间:2023-11-01 01:38:30 24 4
gpt4 key购买 nike

我一直在尝试计算中位数,但我猜还是遇到了一些数学问题,因为我无法获得正确的中位数,也无法弄清楚原因。这是代码;

class StatsCollector {

constructor() {
this.inputNumber = 0;
this.average = 0;

this.timeout = 19000;

this.frequencies = new Map();
for (let i 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;
for (let i 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;
}

}

这是我输入值时的结果快照

342,654,987,1093,2234,6243,7087,20123

enter image description here

正确的结果应该是;

Median: 1663.5

最佳答案

将您的中位数方法更改为:

function median(values){
if(values.length ===0) throw new Error("No inputs");

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;
}

fiddle

关于javascript - 计算中位数 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45309447/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com