Happy pi day! I was busy on the actual day, so I'm slightly late, but I figured I'd share this anyway. ------- TurboWarp ------- TurboWarp is a website to run Scratch projects faster. If the project is slow (or if you just want it to run faster), go to: https://turbowarp.org/985321285?fps=60&turbo ------- How does this work? ------- The idea of the Monte Carlo method of approximating pi is as follows: - Draw a square - Draw a circle such that it perfectly touches the square on all four sides (tangent on all four sides) The radius of the circle is exactly half the side length of the square. Then, repeat the following. The more times you do this (iterations), the more accurate it will be. This project loops this infinitely, so it should in theory get more an more accurate over time (See the end of Notes and Credits for my theory on why it doesn't seem to be working) - Select a random point - If it's in the circle, color it green, add one to your "hits" - If it isn't in the circle, color it red, add one to your "misses" pi should be roughly equal to 4 * Hits / (Hits + Misses) "The area of the circle will be πr^2 and the area of the square will be (2r)^2, so the ratio of the area of the circle to the area of the square will be π/4" - https://programmingpraxis.com/2009/10/09/calculating-pi/#:~:text=An%20interesting%20method%20for%20calculating,square%20will%20be%20%CF%80%2F4.
I have attempted this before, but last time I used a circular sprite to check if the picked point was in the circle. This was unreliable because of Scratch's slightly inaccurate collission checks, especially if they need to be very precise like in this project (and it was hard to scale the circle just right!), so this time I used the distance formula sqrt(x^2 + y^2) instead, and compared it to the radius of the circle. This also significantly speeds up the simulation, as "simple" mathmatical formulas can be calculated a lot faster than sprite collission checks. From my own experience it seems to undershoot pi a lot. This might be because sprites cannot be in between several pixels, and the square therefore might have slightly more area than it's supposed to have relative to the circle. This checks out as when I increased the window size in TurboWarp to the maximum (in the advanced settings) and changed the random x and y values as well as the radius in the code accordingly, I got a more accurate approximation of 3.140 instead of 3.124. Now that I confirmed my theory, I made a project where I increased the radius from 180 to 49500 which seems to be more accurate: