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

标签 scala apache-spark

鉴于以下情况:

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/

相关文章:

java - 如何确定 Apache Spark 中的偏移量?

python - 只能使用分区数相同的 RDD 进行 zip 错误

apache-spark - Spark : persist and repartition order

mysql - 读取端延迟和响应能力

javascript - 如何从 Scala (JVM) 中运行 JavaScript 代码?

scala - 使用Spark中的键优化笛卡尔积

scala - 如何在spark scala中设置数据集的数组类型

scala - 通过命令行更改 'play dist' 输出文件名

json - Play 2.2.2 (Scala) Json parse as List[Class] 问题

apache-spark - 如何在spark sql 2.1.0中的Dataset<Row>上获取groupby之后的所有列