# Ruby PI example - how to calculate PI with Ruby

I was reading a book named Calculus Made Easy, and they note that PI is the limit of the following series:

```4/1 - 4/3 + 4/5 - 4/7 + 4/9 ...
```

## Ruby PI program

It's been a while since I've done much math work, so to test this I wrote the following Ruby PI program.

```#
# ruby pi - how to calculate pi with ruby.
# proving that pi is the limit of this series:
# 4/1 - 4/3 + 4/5 - 4/7 + 4/9 ...
#
num = 4.0
pi = 0
plus = true

den = 1
while den < 10000000
if plus
pi = pi + num/den
plus = false
else
pi = pi - num/den
plus = true
end
den = den + 2
end

puts "PI = #{pi}"              # calculated value of pi
puts "Math::PI = #{Math::PI}"  # pi from the math class
```

After running for a couple of seconds this produces the following output:

```PI = 3.14159245358978
Math::PI = 3.14159265358979
```

It's interesting to see how the calculated value changes when I run the algorithm 100 times, 1,000 times, etc., getting closer and closer to PI as I let the number in the denominator grow larger and larger.

I'm told that the Leibniz series algorithm I've shown here in Ruby is well known for converging very slowly. From the email I received: "The more correct digits you want to calculate the more terms you have to add (for 2 digits ~50 terms, for 3 digits ~500, ...). Thus the algorithm gets slower and slower."

The writer recommends the Brent-Salamin algorithm as a much faster algorithm where "the number of correct digits doubles with each step of the algorithm". Many thanks for the information!

tags:

### I must say your algorithm is

I must say your algorithm is really very slow.

There are much better algorithm

such as PI/4=arctan(1/2)+arctan(1/3)
and
arctan(x)=x-x^3/3+x^5/5-x^7/7+x^9/9.......

that must be much better

### Thanks for the note. This was

Thanks for the note. This was just something fun for me to do with a little downtime. The next time I feel like writing some more code like this I'll try a few different algorithms.