使用C降低数字数组精度的有效方法#

Efficient method for reducing the precision of an array of numbers using C#

提问人:Quantum_Kernel 提问时间:12/12/2022 更新时间:12/12/2022 访问量:114

问:

使用 C#,在不更改类型的情况下将浮点数数组的精度降低 n 位的有效方法是什么?

例:

float[]{1.34, 2.22, 2.32, 7.71}

成为

float[]{1.00, 2.00, 2.00, 8.00}

float[]{1.30, 2.20, 2.30, 7.70}
C# 数组 精度

评论

1赞 theemee 12/12/2022
learn.microsoft.com/en-us/dotnet/api/......
1赞 Robert Harvey 12/12/2022
编写一个循环,循环访问数组,并将每个项目舍入到所需的精度。或者使用 ForEach<T>
2赞 Guru Stron 12/12/2022
您能定义效率标准吗?
0赞 Quantum_Kernel 12/12/2022
我猜遍历数组并使用 Round 函数会起作用。但这似乎太容易了,我认为它可能效率低下。
0赞 Fildor 12/12/2022
取决于。首先以所需的精度获取数据可能会更有效率,仅按需四舍五入可能会更有效率......但是关于拥有浮点数数组并将它们全部舍入到特定的精度,就是这样。

答:

5赞 theemee 12/12/2022 #1
var array = new float[]{1.34f, 2.22f, 2.32f, 7.71f};

for (int i = 0; i < array.Length; i++) {
    array[i] = MathF.Round(array[i], 1); // the second argument is the number of digits after the dot
}

这将修改现有数组,结果将是float[]{1.30f, 2.20f, 2.30f, 7.70f}

如果要创建一个新数组:

var array = new float[]{1.34f, 2.22f, 2.32f, 7.71f};
var roundedArray = array.Select(x => MathF.Round(x, 1)).ToArray(); // or .ToList()