Skip to content

Instantly share code, notes, and snippets.

@tjennings
Created August 5, 2009 21:21
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 tjennings/162977 to your computer and use it in GitHub Desktop.
Save tjennings/162977 to your computer and use it in GitHub Desktop.
val mc = new java.math.MathContext(300,java.math.RoundingMode.HALF_UP)
//Hack to work around poor bigdecimal support in Scala
def divide(a:BigDecimal, b:BigDecimal) = {
new BigDecimal(a.bigDecimal.divide(b.bigDecimal, mc))
}
def piSummands(n: BigDecimal): Stream[BigDecimal] = {
Stream.cons(divide(BigDecimal(1), n), piSummands(n + BigDecimal(2)).map(_ * -1))
}
def scaleStream(stream:Stream[BigDecimal], factor:Int) = {
stream.map( _ * factor)
}
def addStreams(s1:Stream[BigDecimal], s2:Stream[BigDecimal]) = {
s1.zip(s2).map(z => z._1 + z._2)
}
def partialSums(s:Stream[BigDecimal]):Stream[BigDecimal] = {
Stream.cons(s.head, addStreams(s.tail, partialSums(s)))
}
def piStream = scaleStream(partialSums(piSummands(1)), 4)
def square(s:BigDecimal) = s * s
def eulerTransform(s:Stream[BigDecimal]):Stream[BigDecimal] = {
val s0 = s(0)
val s1 = s(1)
val s2 = s(2)
val head = s2 - divide((square(s2 - s1)), ((s0 + (BigDecimal(-2) * s1) + s2)))
Stream.cons(head, eulerTransform(s.tail))
}
type Transform = (Stream[BigDecimal]) => Stream[BigDecimal]
def makeTableau(transform: Transform, s:Stream[BigDecimal]):Stream[Stream[BigDecimal]] = {
Stream.cons(s, makeTableau(transform, transform(s)))
}
def acceleratedSequence(transform:Transform, s:Stream[BigDecimal]) = {
makeTableau(transform, s).map(_.head)
}
print(acceleratedSequence(eulerTransform, piStream).take(150).last)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment