Skip to content
← Back to Community
2 Approximations of π In Only Four Lines of Code!
Profile icon
AmazingMech2418

I just recently noticed I haven't programmed in Python in a while and what better thing to do than approximate π!

After all, it is Pi Python! (Sorry for the poor Markdown rendering. This is supposed to be "Python" with "Py" crossed out and "Pi" inserted.)
(Also, some inspiration from the many π approximation Python repls by

@LizFoster
)

Additionally, I recently completed the codegolf challenges in EcoCode (https://ecocode.mreconomical.repl.co/) by

@MrEconomical
. So, why not combine the two?

And here are two approximations of π using infinite series in just four lines of code!

By the way, for anyone who is wondering, this is the Nilakantha Series and an infinite series for the radian arctangent of 1 multiplied by 4 (in radians, the arctangent of 1 is π/4, although you might just know it as 45 degrees).

And yes, the arctangent method is VERY slow.

**Update: **
New Node.JS version in just one line:
https://repl.it/@AmazingMech2418/Node-p

Voters
Profile icon
NoelB33
Profile icon
TheForArkLD
Profile icon
Codemonkey51
Profile icon
ARJPEG
Profile icon
CodingCactus
Profile icon
LizFoster
Profile icon
AmazingMech2418
Comments
hotnewtop
Profile icon
LizFoster

Yay! Good work!! ^ ^*

Looks really clean, I must say.

Profile icon
AmazingMech2418

@LizFoster
Thank you! However, by "clean", you clearly mean the output, not the actual code, since the actual code is just really jumbled together. However, it is more readable than the Node.JS version I'm working on right now.

Profile icon
LizFoster

@AmazingMech2418
You know, you do not even need that first line: Just plug the values right in!

Profile icon
AmazingMech2418

@LizFoster
What do you mean? The while loop contains the iterations of both methods, requiring the variables. How would you plug in the values?

Profile icon
LizFoster

@AmazingMech2418
Oh, of course #^ __^#

I didn't read it carefully or think about that one, did I?

So sorry....

Profile icon
AmazingMech2418

@LizFoster
It's fine! You probably just missed the while loop. If the while loop weren't there you would be 100% correct.

Profile icon
LizFoster

@AmazingMech2418
Don't tell me my eyes are already going this early.. T~T

Profile icon
AmazingMech2418

@LizFoster
Did you get enough sleep? (I saw the conversation with
@CodingCactus
and what you said in your latest π approximation repl)

Profile icon
LizFoster

@AmazingMech2418
I got enough to function well (around 3 to 4 hours)!
ᕕ( ᐛ )ᕗ

Profile icon
AmazingMech2418

@LizFoster
For me, enough to function well is 7-8 hours... Are you sure 3-4 hours is enough to function well?

Profile icon
LizFoster

@AmazingMech2418
Yeah! wwwww

I don't know how, but I can actually do everyday work on very little sleep. I do not know if that is good, or bad, though..