Created
November 28, 2014 09:41
-
-
Save anonymous/e6e425f1ebd78c981633 to your computer and use it in GitHub Desktop.
Scala.jsFiddle gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Monte Carlo method to calculate Pi digits with an on-line graphic representation of the sample.