Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 27, 2023 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/09ea0bd0d697c7719676bd461b6ef3c2 to your computer and use it in GitHub Desktop.
Save dacr/09ea0bd0d697c7719676bd461b6ef3c2 to your computer and use it in GitHub Desktop.
Compute PI using montecarlo approach, i.e. using a random generator. / published by https://github.com/dacr/code-examples-manager #3cbc2540-3f21-4114-8218-7e461a470bb6/2288ca863469f3be322b04658d6f7503e7a548e
// summary : Compute PI using montecarlo approach, i.e. using a random generator.
// keywords : scala, scalatest, pi, random, algorithm, montecarlo, math, tailrec, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : 3cbc2540-3f21-4114-8218-7e461a470bb6
// created-on : 2020-05-31T19:54:52Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.3.0"
//> using dep "org.scalatest::scalatest:3.2.16"
// ---------------------
import org.scalatest.*, flatspec.*, matchers.*
def monteCarloPI(iterations:Long=10000000L):Double = {
@annotation.tailrec
def worker(in:Long, out:Long, remainingIterations:Long):Double = {
if (remainingIterations==0) 4d*in/(in+out)
else {
val x = Math.random()
val y = Math.random()
if (x * x + y * y > 1) worker(in, out + 1, remainingIterations - 1)
else worker(in + 1, out, remainingIterations - 1)
}
}
worker(0,0,iterations)
}
object pitest extends AnyFlatSpec with should.Matchers {
"pi monte carlo calculus" should "return a precise enough pi value" in {
monteCarloPI() shouldBe 3.14158d +- 0.001d
}
}
pitest.execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment