gpt4 book ai didi

javascript - JavaScript 函数报告的平均值不准确

转载 作者:行者123 更新时间:2023-12-01 01:12:01 25 4
gpt4 key购买 nike

我有一个 average() 方法来计算两个值之间的平均值。平均值相差了小数点的“毛发”。

const measurements = [ 
{ timestamp: '2015-09-01T16:00:00.000Z',
temperature: 27.1,
dewPoint: 16.9
},
{ timestamp: '2015-09-01T16:10:00.000Z',
temperature: 27.3,
dewPoint: 0
},
{ timestamp: '2015-09-01T16:20:00.000Z',
temperature: 27.5,
dewPoint: 17.1
},
{ timestamp: '2015-09-01T16:30:00.000Z',
temperature: 27.4,
dewPoint: 17.3
},
{ timestamp: '2015-09-01T16:40:00.000Z',
temperature: 27.2,
dewPoint: 0
},
{ timestamp: '2015-09-01T17:00:00.000Z',
temperature: 28.1,
dewPoint: 18.3
}
]

为了简洁起见,我不会在这里分享 60 行代码:

假设:

  • 我有一个 query() 方法来获取给定时间戳的范围。在我的示例中from 2015-09-01T16:00:00.000Z 2015-09-01T17:00:00.000Z

  • 另一种方法循环遍历对象并输出minma​​x具有指定指标的值。我的指标是 dewPoint,上述数组的 minma​​x 值为 16.918.3分别是强>。

  • 最后(见下文)一种获取最小值最大值值之间平均值的方法

因此这是上面解释的结果:


// POSTMAN result

[
{
"metric": "dewPoint",
"stat": "min",
"value": 16.9
},
{
"metric": "dewPoint",
"stat": "max",
"value": 18.3
},
{
"metric": "dewPoint",
"stat": "average",
"value": 17.4
}
]

我想获得最大值和最小值之间的平均值。即 16.918.3 应该是 17.6,但是,我得到的是 17.4

这是存在实际错误的一种方法。

function averageMetric(measurements, metric) {

// => metric dewPoint
// => measurements = the data array in example

let value = 0
let measurementsWithMetric = 0
measurements.forEach(measurement => {
if (measurement[metric]) {
value += measurement[metric]
measurementsWithMetric++
}
})
//=> value = 69.6
//=> measurementsWithMetric = 4
const average = value / measurementsWithMetric // Is this the issue?
// average = 17.4

return isNaN(average) ? null : Math.round(average * 100) / 100
}

您能否帮我理解这里的问题,并建议与上述方法等效的 ES6 解决方案?

最佳答案

您的函数计算算术平均值,而不是中间范围。这是一个计算函数:

const measurements = [ 
{temperature: 27.1, dewPoint: 16.9},
{temperature: 27.3, dewPoint: 0}, // Isn't this the minimum value though?
{temperature: 27.5, dewPoint: 17.1},
{temperature: 27.4, dewPoint: 17.3},
{temperature: 27.2, dewPoint: 0},
{temperature: 28.1, dewPoint: 18.3},
{temperature: 28.2}
];
function averageMetric(meas, metr) {
const valid = meas.filter(e => e[metr]);
const min = Math.min(...valid.map(e => e[metr]));
const max = Math.max(...valid.map(e => e[metr]));
return (min + max) / 2;
}

console.log(averageMetric(measurements, 'dewPoint'));

关于javascript - JavaScript 函数报告的平均值不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55083302/

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