java - Scala/Python 与 Java : SparkContext. 映射与 PI 示例中的 .filter?

标签 java python scala mapreduce apache-spark

http://spark.apache.org/examples.html 的 Pi 示例中

在 Estimating Pi 示例中,Python/Scala 与 Java 示例存在差异,我不明白。 Python 和 Scala 都在使用 map 和 reduce:

python

def sample(p):
    x, y = random(), random()
    return 1 if x*x + y*y < 1 else 0

count = spark.parallelize(xrange(0, NUM_SAMPLES)).map(sample) \
             .reduce(lambda a, b: a + b)
print "Pi is roughly %f" % (4.0 * count / NUM_SAMPLES)

斯卡拉

val count = spark.parallelize(1 to NUM_SAMPLES).map{i =>
  val x = Math.random()
  val y = Math.random()
  if (x*x + y*y < 1) 1 else 0
}.reduce(_ + _)
println("Pi is roughly " + 4.0 * count / NUM_SAMPLES)

但是 Java 正在使用过滤器:

int count = spark.parallelize(makeRange(1, NUM_SAMPLES)).filter(new    
  Function<Integer, Boolean>() {
    public Boolean call(Integer i) {
      double x = Math.random();
      double y = Math.random();
      return x*x + y*y < 1;
   }
}).count();
System.out.println("Pi is roughly " + 4 * count / NUM_SAMPLES);

这只是文档拼写错误/错误吗?由于某种原因,过滤器在 Java 中更受欢迎,而 map/reduce 在 Scala 和 Python 中更受欢迎吗?

最佳答案

这些方法是等价的。 Java 代码简单地计算 Scala/Python 映射返回 1 的情况。只是为了让它更透明一点:

def inside(x, y):
    """Check if point (x, y) is inside a unit circle
    with center in the origin (0, 0)"""
    return x*x + y*y < 1

points = ... 

# Scala / Python code is equivalent to this
sum([1 if inside(x, y) else 0 for (x, y) in points])

# While Java code is equivalent to this
len([(x, y) for (x, y) in points if inside(x, y)])

最后得到的总和与圆所覆盖的包围正方形的面积的分数成正比,根据公式我们知道它等于 π。

关于java - Scala/Python 与 Java : SparkContext. 映射与 PI 示例中的 .filter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33900041/

相关文章:

java - 由 Runtime exec 运行时的外部程序 block

python - Cheetah包安装错误-on python 3

python - "in"和 "not in"语句在 python 中如何工作

python - 将多行文本文件拆分为一个列表?

scala - 如何在 sbt 程序集时忽略 Scala 库

scala - Scala中的并发 map /foreach

scala - 向 Spark-jobserver 提交 fat jar 时超时(akka.pattern.AskTimeoutException)

java - 启动时调试 java 应用程序

java - 线程执行期间绘制的额外虚拟组件

java - 通用 Java 移动开发