一、算法
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8eb0c7f8d44d43675df601d61a5f019e.jpeg#pic_center)
二、代码
package org.apache.spark.examples
import scala.math.random
import org.apache.spark.sql.SparkSession
object SparkPi {
def main(args: Array[String]): Unit = {
val spark = SparkSession
.builder.master("local[*]")
.appName("Spark Pi")
.getOrCreate()
val slices = if (args.length > 0) args(0).toInt else 2
val n = math.min(100000L * slices, Int.MaxValue).toInt // avoid overflow
val count = spark.sparkContext.parallelize(1 until n, slices)
.map { i =>
val x = random * 2 - 1
val y = random * 2 - 1
if (x*x + y*y > 1) 1 else 0
// 落于圆外的点少,reduce得快
// if (x*x + y*y <= 1) 1 else 0
}.reduce(_ + _)
println(s"Pi is roughly ${4.0 * (1 - 1.0 * count / (n - 1))}")
// println(s"Pi is roughly ${4.0 * count / (n - 1)}")
spark.stop()
}
}