为什么在reduce中使用减法的结果不一致?

Hap*_*ane 4 scala apache-spark

鉴于以下内容:

val rdd = List(1,2,3)
Run Code Online (Sandbox Code Playgroud)

我假设rdd.reduce((x,y) => (x - y))会返回-4(即(1-2)-3=-4),但它返回2.

为什么?

Tza*_*har 7

从RDD源代码(和文档):

/**
* Reduces the elements of this RDD using the specified commutative and
* associative binary operator.
*/
def reduce(f: (T, T) => T): T
Run Code Online (Sandbox Code Playgroud)

reduce是一个幺半数减少,因此它假定函数是可交换关联的,这意味着不能保证将它应用于元素的顺序.

显然,你的功能(x,y)=>(x-y)不是可交换的,也不是联想的.

在您的情况下,reduce可能是以这种方式应用的:

3 - (2 - 1) = 2
Run Code Online (Sandbox Code Playgroud)

要么

1 - (2 - 3) = 2
Run Code Online (Sandbox Code Playgroud)

  • 只有当你不遵守规则... :)严重,现在,当你想通过你的算法分配,例如,允许火花(或任何其他框架_parallelize_你的计算,你必须"付出代价",这适用于Hadoop还可以在每个节点上执行一些计算,然后聚合结果.这正是这里发生的事情 - 有效地执行`reduce`,每个分区都会减少,然后所有这些中间结果都会再次减少 - 如果你的函数无法处理,那么计算必须是顺序的,这比点... (2认同)