Skip to content

Instantly share code, notes, and snippets.

@ymnk
Created November 17, 2008 07:08
Show Gist options
  • Save ymnk/25682 to your computer and use it in GitHub Desktop.
Save ymnk/25682 to your computer and use it in GitHub Desktop.
import java.math.{BigDecimal => BD, MathContext}
import BD.{ZERO, ONE}
/**
* This program will calculate Pi with John Machin[1]'s formula[2].
* This is just a translation from Mr. Kishida's Java implementation[3] to
* Scala one.
*
* [1] http://en.wikipedia.org/wiki/John_Machin
* [2] http://upload.wikimedia.org/math/f/1/5/f15dc3d39c473c4bd718e3a98145da0d.png
* [3] http://d.hatena.ne.jp/nowokay/20081116#1226837247
*/
object PiMachinBig2{
def main(arg:Array[String]){
val mc=new MathContext(100)
implicit def toBD(i:Int) = new BD(i, mc)
implicit def foo(i:BD) = new {
def /(j:BD) = i.divide(j, mc)
def +(j:BD) = i.add(j)
def *(j:BD) = i.multiply(j)
def -(j:BD) = i.subtract(j, mc)
def unary_- = i.negate
}
var sig = ONE
var a, b = ZERO
val d5 = 5
val d239 = 239
var s1 = ONE / d5
var s2 = ONE / d239
val d5_2:BD = d5*d5
val d239_2:BD = d239*d239
println("start")
val start=System.nanoTime
for(i<-(1 until 140 by 2)){
a = a + ((s1 / i) * sig)
b = b + ((s2 / i) * sig)
s1 = s1 / d5_2
s2 = s2 / d239_2
sig = - sig
}
println((System.nanoTime-start) / 1000 / 1000 / 1000.)
a = a * 16
b = b * 4
println(a - b)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment