Created
August 30, 2012 15:15
-
-
Save jeffreyolchovy/3530567 to your computer and use it in GitHub Desktop.
Revisions
-
jeffreyolchovy revised this gist
Aug 30, 2012 . 1 changed file with 9 additions and 3 deletions.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -1,4 +1,4 @@ import scala.math.{BigInt, BigDecimal} object RecursiveStreams { @@ -11,6 +11,11 @@ object RecursiveStreams // factorials lazy val fac: Stream[BigInt] = Stream.cons(BigInt(1), fac.zip(N).map(a => a._1 * a._2)) // pi / 4 lazy val piOver4: Stream[Double] = Stream.cons(1d, N.map(a => (1 - (a.toDouble % 2) * 2) / (2 * a.toDouble + 1))) def estimatePi(n: Int): Double = piOver4.take(n).sum * 4 def main(args: Array[String]) { assert(N(0) == 1) assert(fib(0) == 0) @@ -22,6 +27,7 @@ object RecursiveStreams println("First 10 natural numbers: %s".format(N.take(10).mkString(" "))) println("First 10 fibonacci numbers: %s".format(fib.take(10).mkString(" "))) println("First 10 factorials: %s".format(fac.take(10).mkString(" "))) println("Pi estimate: %s".format(estimatePi(5000))) } } -
jeffreyolchovy created this gist
Aug 30, 2012 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,27 @@ import scala.math.BigInt object RecursiveStreams { // natural numbers lazy val N: Stream[BigInt] = Stream.cons(BigInt(1), N.map(_ + 1)) // fibonacci series lazy val fib: Stream[BigInt] = Stream.cons(BigInt(0), Stream.cons(BigInt(1), fib.zip(fib.tail).map(a => a._1 + a._2))) // factorials lazy val fac: Stream[BigInt] = Stream.cons(BigInt(1), fac.zip(N).map(a => a._1 * a._2)) def main(args: Array[String]) { assert(N(0) == 1) assert(fib(0) == 0) assert(fac(0) == 1) assert(fib(5) == 5) assert(fac(5) == 120) println("First 10 natural numbers: %s".format(N.take(10).mkString(" "))) println("First 10 fibonacci numbers: %s".format(fib.take(10).mkString(" "))) println("First 10 factorials: %s".format(fac.take(10).mkString(" "))) } }