ivan8m8
ivan8m8

Reputation: 447

Leibniz formula for Pi with a given accuracy

I was asked to calculate the Pi number using the Leibniz formula for Pi with a given accuracy (eps).

The formula looks like this:

enter image description here

Initially, I wrote the following code:

fun main() {
    val eps = 0.005
    var n = 2
    var r = row(n) // current row
    var r0 = row(n-1)
    var s = r0 + r
    
    while (Math.abs(r) > eps) {
        n++
        r = row(n)
        s += r
    }
    println(r.toString() + " <-- Leibniz(" + n.toString() + ")")
    println(Math.abs(s*4).toString() + " <-- our evaluation with eps")
    println(Math.PI.toString() + " <-- real Pi")
    println((Math.abs(s*4)) in (Math.PI-eps..Math.PI+eps))
}

fun row(n: Int) = ((Math.pow(-1.0, n.toDouble()))/(2*n-1))

Then I found out that it doesn't work correctly, because println((Math.abs(s*4)) in (Math.PI-eps..Math.PI+eps)) printed false.

I went deeper, made a debug, and realised that if went with
while (Math.abs(r) > eps/2)
over
while (Math.abs(r) > eps)
everything works fine.

Could someone please provide any explanation on what I did wrong or why I have to divide eps by 2 if that is correct.

Thanks.

Upvotes: 1

Views: 1972

Answers (2)

derpirscher
derpirscher

Reputation: 17390

Each term r_i in that series is summed up to PI with a factor of 4 because sum(r_0, .., r_n) = PI/4. So of course, when you stop at the first r_i <= eps that only means that sum(r_0, ..., r_(i-1)) has an accuray of eps, ie it is somewhere in between [PI/4 - eps/2, PI/4 + eps/2]. But PI it self is 4*sum thus the accuracy is of course 4*eps ie the approximation lies somewhere inbetween [PI-2*eps ,PI+2*eps]

For your value of eps = 0.005:

  • The first r_100 = 0.00497512... is the first r <= eps
  • sum(r0, ..., r_99) = 0.782829, so PI at that point would be approximated as 3.1315929

EDIT

Also you are actually calculating -PI because are flipping the sign of each term in the series. So what you call r0 in your code (it should rather be called r1 because it's the result of row(1)) is -1 instead of +1

Upvotes: 1

al3c
al3c

Reputation: 1452

When you check Math.abs(r) > eps you're looking at the size of the n-th element of the series.

The distance of your current approximation from PI is the sum of all the terms in the series after that one.

As far as I know the relationship between the size of the n-th element of a convergent series and how good of an approximation you have depends on the specific series you are summing.

Upvotes: 0

Related Questions