gpt4 book ai didi

arrays - Ruby:sum 与 inject(:+) 产生不同的结果

转载 作者:数据小太阳 更新时间:2023-10-29 06:46:49 26 4
gpt4 key购买 nike

我注意到 array.sumarray.inject(:+) 产生不同的结果。这是什么原因?

a = [10, 1.1, 6.16]

a.inject(:+)
# => 17.259999999999998

a.sum
# => 17.26

最佳答案

Array#sum 的 C 实现委托(delegate)给 Kahan summation algorithm当它的一些输入是 float 时。

这个算法...

...significantly reduces the numerical error in the total obtained by adding a sequence of finite precision floating point numbers, compared to the obvious approach. This is done by keeping a separate running compensation (a variable to accumulate small errors).

-- Wikipedia

参见 Array#sumimplementation on Github .

关于arrays - Ruby:sum 与 inject(:+) 产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50338948/

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