加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:21:10 所属栏目:安全 来源:网络整理
导读:鉴于以下内容: 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
鉴于以下内容:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读