我正在尝试计算一组 float 的平均值。我需要使用索引,因为这是在二进制搜索中,所以顶部和底部会移动。 (总的来说,我们正在尝试优化半范围估计,因此我们不必每次都重新创建数组)。
无论如何,我写了一个自定义平均循环,我得到的准确度比 c# Average() 方法低 2 位
float test = input.Average();
int count = (top - bottom) + 1;//number of elements in this iteration
int pos = bottom;
float average = 0f;//working average
while (pos <= top)
{
average += input[pos];
pos++;
}
average = average / count;
例子:
0.0371166766 - c# 0.03711666 - my loop 125090.148 - c# 125090.281 - my loop
最佳答案
I'm getting 2 places less accuracy than the c# Average()
不,您只损失了 1 位有效数字。 float 类型只能存储 7 位有效数字,其余的只是随机噪声。在这样的计算中,您不可避免地会累积舍入误差,从而失去精度。平衡舍入误差需要运气。
避免它的唯一方法是使用具有更高精度的浮点类型来累加结果。没问题,您有双可用。这就是 Linq Average 方法看起来像这样的原因:
public static float Average(this IEnumerable<float> source) {
if (source == null) throw Error.ArgumentNull("source");
double sum = 0; // <=== NOTE: double
long count = 0;
checked {
foreach (float v in source) {
sum += v;
count++;
}
}
if (count > 0) return (float)(sum / count);
throw Error.NoElements();
}
使用 double 重现 Linq 结果,结果中的有效数字位数相当。
关于c# float [] average 失去准确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14839309/