package com.shujia.spark.core
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}
import scala.util.Random
object Demo18PI {
def main(args: Array[String]): Unit = {
val conf: SparkConf = new SparkConf()
.setAppName("PI")
.setMaster("local")
val sc = new SparkContext(conf)
val list: Range = 0 until 100000000
//构建一个很大的RDD
val listRDD: RDD[Int] = sc.parallelize(list)
//模拟生成点
val pointRDD: RDD[(Double, Double)] = listRDD.map(i => {
//模拟点
val x: Double = Random.nextDouble() * 2 - 1
val y: Double = Random.nextDouble() * 2 - 1
(x, y)
})
//取出圆内的点
val yuanPointRDD: RDD[(Double, Double)] = pointRDD.filter {
case (x: Double, y: Double) =>
//计算点到圆心的距离
x * x + y * y < 1
}
//计算PI
val PI: Double = yuanPointRDD.count().toDouble / list.length * 4.0
println("PI:"+PI)
}
}