π in Ruby
AmazingMech2418 (1016)

I think I'm pretty much doing pi approximations in every language now, so here it is in Ruby!

Here are the other approximations so far:
Java - https://repl.it/talk/share/p-in-Java/34978
QBasic - https://repl.it/talk/share/p-in-QBasic/34973
Fortran - https://repl.it/talk/share/p-in-Fortran/34890
APL - https://repl.it/talk/share/p-in-APL/34888
Forth - https://repl.it/talk/share/p-in-Forth/34652
LOLCODE - https://repl.it/talk/share/p-in-LOLCODE/34421
Python and Node.js (Node is linked in post) - https://repl.it/talk/share/2-Approximations-of-p-In-Only-Four-Lines-of-Code/32773
C - https://repl.it/talk/share/p-Approximations-in-C/33461

Credit to @TheForArkLD , @Warhawk947 , and @LizFoster for inspiring these approximations. Most of these use the Nilakantha Series, although I also use the arctangent method (multiplying the radian arctangent of 1 by 4 to get pi and getting the arctangent with an infinite series) in three of them (Python, Node, and C).

You are viewing a single comment. View All
theangryepicbanana (1692)

Why are you using global variables? Maybe use a more object-oriented approach like this?

# It turns out that Sonic Pi is based on Ruby, so I already know the basic syntax for Ruby...
class ApproxPi
    def initialize()
        @pi = 3
        @a = 2
        @s = 1
    end
    
    def iterate()
        @pi += @s*(4.0/(@a*(@a*(@a+3.0)+2.0)))
        @a += 2
        @s *= -1
    end
end

approx_pi = ApproxPi.new()

150000.times do
    approx_pi.iterate()
end

puts "pi = #{approx_pi.pi}"

As cool as it is to do this in tons of languages (which I fully support btw), maybe try learning a bit more about each language so each approximation is coded in the "style" of that language (if that makes sense).
Also sonic pi is cool :)

AmazingMech2418 (1016)

@theangryepicbanana The reason I did global variables is because I did not yet know how to do classes in Ruby (of course, I do now that you have shown me this example). Also, with learning a bit more about each language, I completely understand that. My idea behind this, though, was to learn the basics of as many languages as possible and to learn what the languages are best for so that I can learn more about the languages in the future. For example, while I don't think I will use Ruby as much since it is sort of becoming outdated, it is good to have a general idea of the syntax so that I can program in it if I ever need to. Also, by the style of the languages, I'm guessing you mean like how, in the Java approximation, I used a class to store the functions instead of just using a for loop or while loop. If so, I've been trying to do that as much as possible, but just with Ruby, I did not yet really know what that style was. I thought it was more like what I have done in the past with Sonic Pi where I normally used global variables instead of classes.