鉴于以下情况:
val rdd = List(1,2,3)
我假设
rdd.reduce((x,y) => (x - y))
会返回 -4
(即 (1-2)-3=-4
),但它返回了 2
.为什么?
最佳答案
从 RDD 源代码(和 docs ):
/**
* Reduces the elements of this RDD using the specified commutative and
* associative binary operator.
*/
def reduce(f: (T, T) => T): T
reduce
是幺半群归约,因此假设函数是 交换式 和 联想 ,这意味着不能保证将其应用于元素的顺序。显然,您的函数
(x,y)=>(x-y)
不是可交换的,也不是结合的。在您的情况下,reduce 可能已以这种方式应用:
3 - (2 - 1) = 2
或者
1 - (2 - 3) = 2
关于scala - 为什么在reduce中使用减法结果不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36813443/