Last active
May 25, 2024 10:19
-
-
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/1293f8ee4426a0a17ca030e9b409940bb070fa96
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
// 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.4.2" | |
//> 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