This is because this function is already defined in. Note: Please notice that we didn’t defined the dist function that calculates the distance between two points. This will vary with each execution due to the random function used… but nevertheless notice that whatever result you’ll get will be pretty close to the actual π value, which is pretty incredible for such simple empirical method! If you copy the above code in the editor and run it, you will see the result displayed: 3.1496 var p = calcPI() įor(var i = 0 i π = 4 * area_circle / area_square We can implement this algorithm using only pure JavaScript without drawing circles or squares. In this article we will use the free environment (you just need to create a free account to use it).Īlthough we talked until now only about graphical concepts, the code won’t use any graphical library. You can use any JavaScript environment or playground to write the code. Now we have all the data we need to start writing the JavaScript code that will calculate π. Of course, throwing darts is a simple random operation that need to be repeated many, many times in order to get a relevant result. Step 4: Calculate π by using formula π = (4 * circlePoints) / totalPoints.Step 3: Count how many darts are falling in the circle (e.g.Step 2: Count how many darts we throw in total (e.g.We will assume we have a good enough aim and all the darts will hit at least the square. Step 1: Throw random darts at the target.Let’s put the above observation is an algorithm: The catch is no not calculate areas by mathematical means, but instead randomly throw darts towards the canvas… which after a while we expect to cover the entire area of square and of course circle. Look at the previous picture and notice that:īy solving these equations for π we will find out that: However instead of measuring the area of the circle and then solving the equation for π we will start throwing random darts at the target.īefore we start our implementation let’s do a little bit of math. In this article we will use the same setup of enclosing a circle inside a tight square. In the previous article we saw how to approximate π by calculating the area of a circle using JavaScript.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |