Skip to content

Instantly share code, notes, and snippets.

Created November 28, 2014 09:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/e6e425f1ebd78c981633 to your computer and use it in GitHub Desktop.
Save anonymous/e6e425f1ebd78c981633 to your computer and use it in GitHub Desktop.
Scala.jsFiddle gist
object ScalaJSExample extends js.JSApp{
def pi(n: Int, tracer: ((Double, Double, Boolean) => Unit)) = {
import scala.util.Random.nextDouble
import scala.math.hypot
def inQuadrant(a: Double, b: Double): Boolean = hypot(a,b)<=1.0
def trySum(n: Int, m: Int): Double = n match {
case 0 => m
case _ => {
val a = nextDouble
val b = nextDouble
val incircle = inQuadrant(a, b)
tracer(a, b, incircle)
trySum(n-1, m+{if(incircle) 1 else 0})
}
}
4.0*trySum(n, 0).toDouble/n.toDouble
}
val (w, h) = (Page.canvas.height.toDouble, Page.canvas.height.toDouble)
def pointTracer(a: Double, b: Double, inarea: Boolean) = {
Page.renderer.fillStyle = if(inarea) "green" else "red"
Page.renderer.fillRect(a*w, b*(h-25), 1, 1)
}
def main() = {
var currentSum = 0.0;
var currentN = 0;
val step = 10;
dom.setInterval(() => {
currentSum += pi(step,pointTracer)
currentN += 1
Page.renderer.fillStyle = "black"
Page.renderer.fillRect(0, h-20, w, 20)
Page.renderer.fillStyle = "white"
Page.renderer.fillText("Pi: " + (currentSum/currentN) toString , 10, h)
}, 5)
}
}
@pfcoperez
Copy link

Monte Carlo method to calculate Pi digits with an on-line graphic representation of the sample.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment