less than 1 minute read

It’s pi day, so I wanted to celebrate with a python one-liner I wrote that approximates pi:

from random import random as r
print("pi~=", sum([(r()-0.5)**2+(r()-0.5)**2<0.5**2 for n in range(int(1e6))])/(1e6*0.5**2))
pi~= 3.14155052

Yes, I can hear you already, it’s technically two lines, but I needed a random number generator. At least I didn’t use the math module 🙄

This code is obfuscated on purpose. If you want to find out how the algorithm works in detail, and how to implement it in a much cleaner way, check out this colab: