DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Paul Lefebvre
Paul Lefebvre

Posted on

Pi Day: Estimating the value of Pi

It's Pi day (March 14) and one question you may be wondering is β€œhow is Pi calculated?”

Measuring circles can give a rough estimate, but an infinite series is perhaps a better and more common way to do it. As described on Calculating Pi at MathCareers.org.uk, the Nilakantha Series works pretty well. Its formula looks like this:

Nilakantha Series: Ο€ = 3 + 4 / (2Γ—3Γ—4) βˆ’ 4 / (4Γ—5Γ—6) + 4 / (6Γ—7Γ—8) βˆ’ 4 / (8Γ—9Γ—10) + …

You ought to be able to figure out a pattern from that. And it’s a short leap to convert that to Xojo code. Here’s code that calculates Pi using the Nilakantha Series:

Dim even As Boolean = True
Dim calc As Double
Dim calcStart As Int64

Dim iterations As Integer
While iterations < 1000
  iterations = iterations + 1
  calcStart = calcStart + 2
  calc = 4.0 / (calcStart * (calcStart + 1) * (calcStart + 2))

  If even Then
    Pi = Pi + calc
  Else
    Pi = Pi - calc
  End If

  even = Not even
Wend
Enter fullscreen mode Exit fullscreen mode

Here’s a completed project you can run in Xojo: CalcPi Project

The above code correctly calculated the first 9 digits of Pi almost immediately. Unfortunately, calculating more digits of Pi is not really practical using the standard double-precision floating point data type used in most programming languages.

Top comments (1)

Collapse
 
dkassen profile image
Daniel Kassen

Paul your posts are awesome. Keep β€˜em coming!

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.