Almkvist-Giullera formula for pi: Difference between revisions
Content added Content deleted
m (→{{header|RPL}}: improved layout) |
(Add Scala implementation) |
||
Line 2,297: | Line 2,297: | ||
1: iterations:53 |
1: iterations:53 |
||
</pre> |
</pre> |
||
=={{header|Scala}}== |
|||
<syntaxhighlight lang="Scala"> |
|||
import java.math.{BigDecimal, BigInteger, MathContext, RoundingMode} |
|||
object AlmkvistGiulleraFormula extends App { |
|||
println("n Integer part") |
|||
println("================================================") |
|||
for (n <- 0 to 9) { |
|||
val term = almkvistGiullera(n).toString |
|||
println(f"$n%1d" + " " * (47 - term.length) + term) |
|||
} |
|||
val decimalPlaces = 70 |
|||
val mathContext = new MathContext(decimalPlaces + 1, RoundingMode.HALF_EVEN) |
|||
val epsilon = BigDecimal.ONE.divide(BigDecimal.TEN.pow(decimalPlaces)) |
|||
var previous = BigDecimal.ONE |
|||
var sum = BigDecimal.ZERO |
|||
var pi = BigDecimal.ZERO |
|||
var n = 0 |
|||
while (pi.subtract(previous).abs.compareTo(epsilon) >= 0) { |
|||
val nextTerm = new BigDecimal(almkvistGiullera(n)).divide(BigDecimal.TEN.pow(6 * n + 3)) |
|||
sum = sum.add(nextTerm) |
|||
previous = pi |
|||
n += 1 |
|||
pi = BigDecimal.ONE.divide(sum, mathContext).sqrt(mathContext) |
|||
} |
|||
println("\npi to " + decimalPlaces + " decimal places:") |
|||
println(pi) |
|||
def almkvistGiullera(aN: Int): BigInteger = { |
|||
val term1 = factorial(6 * aN).multiply(BigInteger.valueOf(32)) |
|||
val term2 = BigInteger.valueOf(532 * aN * aN + 126 * aN + 9) |
|||
val term3 = factorial(aN).pow(6).multiply(BigInteger.valueOf(3)) |
|||
term1.multiply(term2).divide(term3) |
|||
} |
|||
def factorial(aNumber: Int): BigInteger = { |
|||
var result = BigInteger.ONE |
|||
for (i <- 2 to aNumber) { |
|||
result = result.multiply(BigInteger.valueOf(i)) |
|||
} |
|||
result |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
n Integer part |
|||
================================================ |
|||
0 96 |
|||
1 5122560 |
|||
2 190722470400 |
|||
3 7574824857600000 |
|||
4 312546150372456000000 |
|||
5 13207874703225491420651520 |
|||
6 567273919793089083292259942400 |
|||
7 24650600248172987140112763715584000 |
|||
8 1080657854354639453670407474439566400000 |
|||
9 47701779391594966287470570490839978880000000 |
|||
pi to 70 decimal places: |
|||
3.1415926535897932384626433832795028841971693993751058209749445923078164 |
|||
</pre> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |