Last active
May 25, 2024 10:19
-
-
Save dacr/fb5503656b0de238c59980c98893c11b to your computer and use it in GitHub Desktop.
compute exponential e high precision value / published by https://github.com/dacr/code-examples-manager #cd88fb58-3717-4528-88f1-b3286c541cd2/8950a35618a89737d1db2dc6649287732044787b
This file contains hidden or 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 exponential e high precision value | |
// keywords : scala, math, e, math, mathcontext, precision, scale, @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 : cd88fb58-3717-4528-88f1-b3286c541cd2 | |
// created-on : 2021-02-09T08:58:06Z | |
// 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" | |
//> using objectWrapper | |
// --------------------- | |
import org.scalatest._ | |
import flatspec._ | |
import matchers._ | |
import scala.math.BigDecimal.RoundingMode | |
import scala.math._ | |
def e(iter:Int):BigDecimal = { | |
val from = BigDecimal(1, java.math.MathContext.UNLIMITED) | |
LazyList | |
.iterate( (1, from, BigDecimal(1)) ) { case (n, result, fact) => | |
val newFact = fact * n | |
val newResult = result + 1/newFact | |
(n+1, newResult, newFact) | |
}.collect {case (n, result, _) if iter == n => result} | |
.head | |
} | |
class ETest extends AnyFlatSpec with should.Matchers { | |
override def suiteName: String = "FactTest" | |
"e" should "return the right result" in { | |
e(20).toDouble shouldBe E | |
} | |
it should "give high precision value" in { | |
val computed = e(2000).setScale(5000, RoundingMode.FLOOR) | |
info(computed.toString) | |
} | |
} | |
org.scalatest.tools.Runner.main(Array("-oDF", "-s", classOf[ETest].getName)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment