{"id":"c1359961cb5c9ccb","slug":"mathe-carlo/2","trashed":false,"description":"","likes":11,"publish_level":"public","forks":0,"fork_of":null,"has_importers":false,"update_time":"2019-11-25T02:27:31.626Z","first_public_version":null,"paused_version":null,"publish_time":"2019-11-22T16:33:06.529Z","publish_version":1860,"latest_version":1860,"thumbnail":"dc2c4bfa7f523aaec54c42b274b869ded157a5fbb2c495aeb37c5285297d357e","default_thumbnail":"fc5adeab99ed96c1fe2e7ae4d6eab651b0313db6587f6c93ca9c56827a2fe6cc","roles":[],"sharing":null,"owner":{"id":"48f1e3a2c060ae68","avatar_url":"https://avatars.observableusercontent.com/avatar/bda6c3496a42e5c82807878bf038b4173d7b9dd808f8ec5ab3dd753e73b393bd","login":"jajoosam","name":"Samarth Jajoo","bio":"17 year old learner and maker of things.","home_url":"https://sam.jajoo.fun","type":"team","tier":"starter_2024"},"creator":{"id":"eaf2213e95a3f7ab","avatar_url":"https://avatars.observableusercontent.com/avatar/bda6c3496a42e5c82807878bf038b4173d7b9dd808f8ec5ab3dd753e73b393bd","login":"jajoosam","name":"Samarth Jajoo","bio":"17 year old learner and maker of things.","home_url":"https://sam.jajoo.fun","tier":"public"},"authors":[{"id":"eaf2213e95a3f7ab","avatar_url":"https://avatars.observableusercontent.com/avatar/bda6c3496a42e5c82807878bf038b4173d7b9dd808f8ec5ab3dd753e73b393bd","name":"Samarth Jajoo","login":"jajoosam","bio":"17 year old learner and maker of things.","home_url":"https://sam.jajoo.fun","tier":"public","approved":true,"description":""}],"collections":[],"files":[],"comments":[],"commenting_lock":null,"suggestion_from":null,"suggestions_to":[],"version":1860,"title":"Mathe Carlo","license":null,"copyright":"","nodes":[{"id":0,"value":"md`# Mathe Carlo`","pinned":false,"mode":"js","data":null,"name":null},{"id":458,"value":"md `## An exploration and explanation of the [Monte Carlo](https://en.wikipedia.org/wiki/Monte_Carlo_method) method. `","pinned":false,"mode":"js","data":null,"name":null},{"id":997,"value":"md`This is a computational essay on the Monte Carlo method - some math that really seems like magic to me. The premise of this method is straightforward: Calculating probabilities by giving a simulation **lots** of random inputs.`","pinned":false,"mode":"js","data":null,"name":null},{"id":1001,"value":"md`If that doesn't make sense, I hope this essay is able to show you why this is as cool as I think it is. I want to make this explanation one that seems intuitive, and like an experiment!`","pinned":false,"mode":"js","data":null,"name":null},{"id":1005,"value":"md`Everything on this page can be seen from behind the scenes - and you can see how I've done a particular calculation, or my method for generating inputs at any point by peeking at the code.`","pinned":false,"mode":"js","data":null,"name":null},{"id":1010,"value":"md`Enjoy - and please send over any feedback to [@jajoosam](https://twitter.com/jajoosam) or email sam@jajoo.fun.`","pinned":false,"mode":"js","data":null,"name":null},{"id":570,"value":"md`## 🥧 Approximating Pi `","pinned":false,"mode":"js","data":null,"name":null},{"id":1013,"value":"md`Pi is an essential ratio, for any computation to do with a circle. Through the last 4000 years - we've used all kinds of methods to calculate ${tex`\\pi`} - from estimating ranges of values by treating the [circle as a polygon](https://www.youtube.com/watch?v=_rJdkhlWZVQ), to creating a whole lot of [different infinite series](http://www.geom.uiuc.edu/~huberty/math5337/groupe/expresspi.html).`","pinned":false,"mode":"js","data":null,"name":null},{"id":1018,"value":"md`Let's try using the Monte Carlo method to approximate ${tex`\\pi`}! The goal here is not to get a super accurate value, instead: I want this to serve as an example that showcases the beauty of this method ✨`","pinned":false,"mode":"js","data":null,"name":null},{"id":6,"value":"{\n  var rect = two.makeRectangle((two.width/2), (two.width/2), two.width, two.width);\n\n  var circle = two.makeCircle((two.width/2), (two.width/2), (two.width/2));\n  console.log(circle);\n\n  circle.fill = '#FF8000';\n  rect.fill = '#00c8ff';\n\n  two.update();\n\n  return md`First up - We're drawing a big circle, completely enclosed in a square.`\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":81,"value":"shape = html`<div class=\"circ block wrapper fixed\"></div>`; ","pinned":false,"mode":"js","data":null,"name":null},{"id":1392,"value":"viewof circleInputs = {\n  let a = html`<button class=\"block inline\" style=\"padding: 5px\">Add 1 point</button>`;\n  a.onclick = () => mutable toAddCircle = 1;\n  let b = html`<button  class=\"block inline accent\" style=\"padding: 5px\">Add 10 points</button>`\n  b.onclick = () => mutable toAddCircle = 10;\n  let c = html`<button  class=\"block inline\" style=\"padding: 5px\">Add 100 points</button>`\n  c.onclick = () => mutable toAddCircle = 100;\n  return html`${a} ${b} ${c}`;\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":176,"value":"{\n  // this adds a point randomly within the blue square\n  for (var i = 0; i < toAddCircle; i++) {\n    // getting a random point that fits in the square\n    let x = rand(0, two.width);\n    let y = rand(0, two.height);\n    let center = two.width / 2;\n\n    let color = \"white\";\n    // the line below is the checking if √(x-center)² + (y-center)² ≤ the radius of the circle (two.width/2)\n    // hence seeing if the point is within the circle or not!\n\n    if (\n      Math.sqrt(\n        Math.pow(Math.abs(x - two.width / 2), 2) +\n          Math.pow(Math.abs(y - two.height / 2), 2)\n      ) <=\n      two.width / 2\n    ) {\n      mutable inside += 1;\n      color = \"green\";\n    }\n\n    mutable total += 1;\n\n    // plot the point\n    two.makeCircle(x, y, 3, 3).fill = color;\n  }\n  // update the shape\n  two.update();\n\n  return md`Add points to the shape by hitting the buttons above. \n\n**Try hitting the three dots on the left, and hit 'edit' to see the JavaScript code that powers this demo.**`;\n}\n","pinned":false,"mode":"js","data":null,"name":null},{"id":1440,"value":"md`Here's a live updating count of the points added in total, and inside the circle.`","pinned":false,"mode":"js","data":null,"name":null},{"id":192,"value":"mutable inside = 0;","pinned":false,"mode":"js","data":null,"name":null},{"id":231,"value":"mutable total = 0;","pinned":false,"mode":"js","data":null,"name":null},{"id":304,"value":"md`#### We can compute a neat ratio with that: ${tex`\\frac {inside \\, the \\, circle} {total \\, points} = \\frac {${inside}} {${total}}`}`","pinned":false,"mode":"js","data":null,"name":null},{"id":324,"value":"md `By plotting points randomly in our shape, we get the fraction above. \n\nWhat we're calculating here is the probability of the plotted point being **inside** the circle.`","pinned":false,"mode":"js","data":null,"name":null},{"id":334,"value":"md`Turns out we can do somthing really neat with this probability - approximate the value of ${tex`\\pi`}.\n\nWe can do this because our ratio should be proportional to the ratios of the areas of the inner circle, and the square.\n`","pinned":false,"mode":"js","data":null,"name":null},{"id":343,"value":"md `Let's start off by comparing the area of a circle with radius *r*, and a square with side *2r*.`","pinned":false,"mode":"js","data":null,"name":null},{"id":349,"value":"md`**Square**\n\n${tex`Area = (2r)^2 = (2)^2 \\times r^2 = 4 \\times r^2`}`","pinned":false,"mode":"js","data":null,"name":null},{"id":361,"value":"md`**Circle**\n\n${tex`Area = \\pi \\times r^2`}`","pinned":false,"mode":"js","data":null,"name":null},{"id":371,"value":"md`We can compare our two ratios now:\n\n**points inside the circle** : **total points plotted**\n\nto\n\n**area of circle** : **area of square**` ","pinned":false,"mode":"js","data":null,"name":null},{"id":369,"value":"md`## ${tex`\\frac {inside \\, the \\, circle} {total \\, points} = \\frac {${inside}} {${total}} \\approx \\frac {area \\, of \\, circle} {area \\, of \\, square}`}`","pinned":false,"mode":"js","data":null,"name":null},{"id":388,"value":"md `## ${tex`\\frac {${inside}} {${total}} \\approx \\frac {\\pi \\times r^2} {4 \\times r^2} \\approx \\frac {\\pi \\times \\cancel {r^2}} {4 \\times \\cancel {r^2}} \\approx \\frac \\pi 4`} `","pinned":false,"mode":"js","data":null,"name":null},{"id":422,"value":"md `Nice! Our ratio is approximately one fourth of ${tex`\\pi`}. `","pinned":false,"mode":"js","data":null,"name":null},{"id":427,"value":"md`### ${tex`\\pi \\approx 4 \\times \\frac {${inside}} {${total}} \\approx ${((inside/total)*4).toFixed(3)}`}`","pinned":false,"mode":"js","data":null,"name":null},{"id":1460,"value":"viewof circleInputs2 = {\n  let a = html`<button class=\"block inline\" style=\"padding: 5px\">Add 1 point</button>`;\n  a.onclick = () => mutable toAddCircle = 1;\n  let b = html`<button  class=\"block inline accent\" style=\"padding: 5px\">Add 10 points</button>`\n  b.onclick = () => mutable toAddCircle = 10;\n  let c = html`<button  class=\"block inline\" style=\"padding: 5px\">Add 100 points</button>`\n  c.onclick = () => mutable toAddCircle = 100;\n  return html`${a} ${b} ${c}`;\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":462,"value":"md `That's it! Try adding more points to see how accurate your value can get to Pi. \n\nHere are the exact numbers we're calculating with 👇`","pinned":false,"mode":"js","data":null,"name":null},{"id":273,"value":"approxPi = (inside/total)*4","pinned":false,"mode":"js","data":null,"name":null},{"id":434,"value":"actualPi = Math.PI","pinned":false,"mode":"js","data":null,"name":null},{"id":279,"value":"piError = `${Math.abs(100-(approxPi/actualPi)*100).toFixed(2)}%`","pinned":false,"mode":"js","data":null,"name":null},{"id":1025,"value":"md`### Wait... what'd we do here?`","pinned":false,"mode":"js","data":null,"name":null},{"id":1028,"value":"md`We just came up with a value for pi - by drawing random points inside a square 😮\n\nThat's what so cool about the Monte Carlo method: we're able to get concrete approximations, by performing *random* actions.\n\nIn fact, it's so random that people actually tried to calculate pi by [throwing darts](https://www.youtube.com/watch?v=M34TO71SKGk) - and it worked!`","pinned":false,"mode":"js","data":null,"name":null},{"id":879,"value":"md`### Deviation and error: measuring spread, why it matters`","pinned":false,"mode":"js","data":null,"name":null},{"id":808,"value":"md`Here, I've used the Monte Carlo method to approximate pi, with different numbers of points to measure the change in error, and deviation.`","pinned":false,"mode":"js","data":null,"name":null},{"id":855,"value":"md`Pi is being computed 1000 times here, and the total points plotted for each computation is in multiples of 100.\n\nThe first set of computations of pi is based on a total of 100 plotted points, while the final set is based on a total of 5000 plotted points.`","pinned":false,"mode":"js","data":null,"name":null},{"id":902,"value":"md`Each set of computations includes 20 different values of Pi, calculated with the same number of total point plotted. We're doing this so that we can measure spread.`","pinned":false,"mode":"js","data":null,"name":null},{"id":851,"value":"{\n go; // shows the new values everytime we recalculate\n return piData\n} // hit the ▶ to explore the data","pinned":false,"mode":"js","data":null,"name":null},{"id":863,"value":"md`There's our data from the computation - if you try exploring it, you'll see each element in the array has these properties:\n- **count** (total points plotted)\n- **mean** (the mean of 20 different computed values of pi)\n- **deviation** (a measure of how much the computed values vary from their mean)\n- **error** (% error from the real value of pi)`","pinned":false,"mode":"js","data":null,"name":null},{"id":870,"value":"md`Now, let's make a graph of the error in ${tex`\\pi`} vs. the points plotted 👇`","pinned":false,"mode":"js","data":null,"name":null},{"id":665,"value":"{\n  b;\n  piData.length = 0;\n  let vals = [];\n  for(var k = 1; k<51; k++){\n    for(var j = 0; j<20; j++){\n      // this adds a point randomly within the blue square\n      let in1 = 0;\n      let to1 = 0;\n      for(var i = 0; i<(k*100); i++){\n\n        // getting a random value between 0 and 500\n        let x = Math.random()*two.width;\n        let y = Math.random()*two.height;\n\n        // calculating if the point is within the circle with pythagoras.\n        if(Math.sqrt(Math.pow(Math.abs(x-(two.width/2)), 2) + Math.pow(Math.abs(y-(two.width/2)),2))<=(two.width/2)){ \n          in1+=1;\n        }\n\n        to1+=1;\n      }\n      vals.push(4*(in1/to1))\n    }\n    \n\n\n    let out = {\n      mean: mean(vals),\n      deviation: deviation(vals),\n      error: Math.abs(100-(mean(vals)/Math.PI)*100),\n      count: k*100\n    }\n    piData.push(out)\n  }\n  mutable go += 1;\n  return plot(piData, {key: 'count', name: 'total points plotted'}, {key: 'error', name: '% error'});\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":934,"value":"md`The % error generally seems to reduce as the number of points we plot increase.`","pinned":false,"mode":"js","data":null,"name":null},{"id":937,"value":"md`Let's make another graph - this time of the deviation in our values of ${tex`\\pi`} vs. the points plotted 👇` ","pinned":false,"mode":"js","data":null,"name":null},{"id":940,"value":"{ \n  go;\n  return plot(piData, {key: 'count', name: 'total points plotted'}, {key: 'deviation', name: 'standard deviation'});\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":943,"value":"md`Huh - deviation seems to decrease as our count increases too. This tells us that the data gets less spread out as we plot more points - our calculated values seem to be approaching a particular ratio (${tex`\\pi`})!`","pinned":false,"mode":"js","data":null,"name":null},{"id":964,"value":"md`And as it (usually) seems: as deviation reduces, so does the error in our computed values of ${tex`\\pi`}:`","pinned":false,"mode":"js","data":null,"name":null},{"id":948,"value":"{\n  go;\n  return plot(piData, {key: 'deviation', name: 'standard deviation'}, {key: 'error', name: '% error'}, true);\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":914,"value":"md`This proves that the Monte Carlo method works for approximating pi! The ratio we get is not arbitrary, and in fact, it continues to become more accurate as we work with a bigger number of points.`","pinned":false,"mode":"js","data":null,"name":null},{"id":977,"value":"md`Hit this button to calculate new values, and plot the graphs again - and see for yourself if this trend actually stays:`","pinned":false,"mode":"js","data":null,"name":null},{"id":973,"value":"viewof b = html`<button class=\"block accent\">Replot</button>`","pinned":false,"mode":"js","data":null,"name":null},{"id":581,"value":"md`## 👨‍🔬 Integrating the curve of ${tex`y = x^2`}`","pinned":false,"mode":"js","data":null,"name":null},{"id":642,"value":"md`It's pretty useful to integrate the area under curves - we can find all kinds of useful information once we know the area under a function.`","pinned":false,"mode":"js","data":null,"name":null},{"id":1456,"value":"md`However, sometimes integrals can be super complicated - and sometimes it might just be too difficult to define the function. The Monte Carlo method is super helpful here - it can be used as a bruteforce approach to approximating an integral!`","pinned":false,"mode":"js","data":null,"name":null},{"id":1037,"value":"md`**We can use the same concept we used to approximate pi to integrate!**\n\nLet's compare the ratio of points ${tex`\\frac {under\\,the\\,curve} {total\\,points\\,plotted}`} to the ${tex`\\frac {area\\,under\\,the\\,curve}{area\\,of \\,rectangle}`}.`","pinned":false,"mode":"js","data":null,"name":null},{"id":597,"value":"view = html`<div style=\"width: 100%; height: ${500}px\"  class=\"block wrapper fixed\" id=\"graph\" style=\"overflow: shown\"></div>`;","pinned":false,"mode":"js","data":null,"name":null},{"id":600,"value":"{\n  let func = graph.create('functiongraph', [function(x){return Math.pow(x, 2);}, -3, 3])\n  graph.create('inequality', [func], {boundingbox: [-3, -1, 3, 5]});\n  return md`Let's plot a graph of ${tex`y = x^2, \\,\\, \\text{where} -3<x<3`}`\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":1443,"value":"md`What's the area under this graph (*the red, highlighted portion*)? We can find out by integrating ${tex`x^2`} within limits *-3* and *3*.`","pinned":false,"mode":"js","data":null,"name":null},{"id":603,"value":"tex`\\int_{-3}^{3}x^2dx = \\frac {3^3} {3} - \\frac {-3^3} {3} = 9 - (-9) = 18`","pinned":false,"mode":"js","data":null,"name":null},{"id":606,"value":"md`By integration, we know that the area under the ${tex`x^2`} curve is 18 units.`","pinned":false,"mode":"js","data":null,"name":null},{"id":609,"value":"md`Let's use the Monte Carlo method to calculate the area under the curve - hopefully we get something close!`","pinned":false,"mode":"js","data":null,"name":null},{"id":612,"value":"viewof graphInputs = {\n  let a = html`<button class=\"block inline\" style=\"padding: 5px\">Add 1 point</button>`;\n  a.onclick = () => mutable toAddGraph = 1;\n  let b = html`<button class=\"block inline accent\" style=\"padding: 5px\">Add 10 points</button>`\n  b.onclick = () => mutable toAddGraph = 10;\n  let c = html`<button class=\"block inline\" style=\"padding: 5px\">Add 100 points</button>`\n  c.onclick = () => mutable toAddGraph = 100;\n  return html`${a} ${b} ${c}`;\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":615,"value":"{\n  toAddGraph;\n  // this adds a point randomly within the blue square\n  for(var i = 0; i<toAddGraph; i++){\n    \n    // getting a random value between 0 and 500\n    let x = rand(-3,3)\n    let y = rand(0,9)\n    let color = 'green'\n     \n    // checking if the point is under the graph - if x² > y\n    if(Math.pow(x,2)>y){ \n      mutable underGraph+=1;\n      color = 'orange';\n    }\n    \n    graph.create('point', [x, y], {color})\n    \n    mutable totalGraph+=1;\n  }\n  return md`Hitting **Add** will randomly plot points inside the graph, where ${tex`-3<x<3`}`\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":1451,"value":"md`Here's a live count of the total points, as well as the points plotted below the curve.`","pinned":false,"mode":"js","data":null,"name":null},{"id":618,"value":"mutable totalGraph = 0;","pinned":false,"mode":"js","data":null,"name":null},{"id":619,"value":"mutable underGraph = 0;","pinned":false,"mode":"js","data":null,"name":null},{"id":625,"value":"md`Our curve can be enclosed in a ${tex`6 \\times 9`} box, since ${tex`-3<x<3`} and ${tex`0<y<9`}.`","pinned":false,"mode":"js","data":null,"name":null},{"id":629,"value":"md`We can use our ratio of ${tex`\\frac {under} {total} = \\frac {${underGraph}} {${totalGraph}}`}`","pinned":false,"mode":"js","data":null,"name":null},{"id":631,"value":"md`Multiplying this ratio with the area of the ${tex`6 \\times 9`} box should result in an approximation of the area under the graph.`","pinned":false,"mode":"js","data":null,"name":null},{"id":633,"value":"md`### ${tex`\\frac {${underGraph}} {${totalGraph}} \\times 6 \\times 9 \\approx {area \\, under \\, graph} \\approx ${((underGraph/totalGraph)*6*9).toFixed(3)}`}` ","pinned":false,"mode":"js","data":null,"name":null},{"id":1463,"value":"viewof graphInputs2 = {\n  let a = html`<button class=\"block inline\" style=\"padding: 5px\">Add 1 point</button>`;\n  a.onclick = () => mutable toAddGraph = 1;\n  let b = html`<button class=\"block inline accent\" style=\"padding: 5px\">Add 10 points</button>`\n  b.onclick = () => mutable toAddGraph = 10;\n  let c = html`<button class=\"block inline\" style=\"padding: 5px\">Add 100 points</button>`\n  c.onclick = () => mutable toAddGraph = 100;\n  return html`${a} ${b} ${c}`;\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":635,"value":"md`As you add more points, this number should come closer and closer to **18**.`","pinned":false,"mode":"js","data":null,"name":null},{"id":1122,"value":"md`## Why is it called *Monte Carlo*?`","pinned":false,"mode":"js","data":null,"name":null},{"id":1129,"value":"html`<div class=\"block wrapper\"><img src=\"https://lonelyplanetimages.imgix.net/a/g/hi/t/d6dbfeb4a839afa6e09adbe525674de3-casino-de-monte-carlo.jpg\" style=\"max-width: 100%; width: 500px; display:block\"></div>`","pinned":false,"mode":"js","data":null,"name":null},{"id":1142,"value":"md`The ward of *Monte Carlo* is especially famous for its super big casino. \n\nAs you can guess, the Monte Carlo method lets us make some interesting conclusion about casino games too!`","pinned":false,"mode":"js","data":null,"name":null},{"id":1147,"value":"md`### Roulette`","pinned":false,"mode":"js","data":null,"name":null},{"id":1150,"value":"html`<img src=\"https://upload.wikimedia.org/wikipedia/commons/5/5d/American_roulette_wheel_layout.png\" width=\"300px\">`","pinned":false,"mode":"js","data":null,"name":null},{"id":1155,"value":"md`The roulette ring is divided into 38 sections - two divisions are **0**s, and the others are labelled from 1-36.\n\n\nLet's say we make high/low bets here: we predict whether the ball settles on a number between 19-36(high) or 1-18(low). If we're correct - we win the amount of money we bet, along with getting it back.\n\nAnything else, and we lose our money 🤞`","pinned":false,"mode":"js","data":null,"name":null},{"id":1162,"value":"md`Play a round of roulette right here (you're betting low!):`","pinned":false,"mode":"js","data":null,"name":null},{"id":1197,"value":"viewof playRoulette = html`<button class=\"block accent\">Bet $</button>`","pinned":false,"mode":"js","data":null,"name":null},{"id":1165,"value":"{\n playRoulette;\n // generating a random number from -1 to 38; (-1 and 0 are the two zeros)\n let division = Math.floor(rand(-1,39)) \n \n if(division > 0 && division < 19){\n  mutable rouletteWinCount++;\n  return(`Win 🥳 - the ball settled on ${division}!`)\n }\n  \n else{\n  mutable rouletteLossCount++;\n  return(`Lose 😞 - the ball settled on ${division}!`)\n }\n  \n}","pinned":false,"mode":"js","data":null,"name":null},{"id":1172,"value":"mutable rouletteWinCount = 0","pinned":false,"mode":"js","data":null,"name":null},{"id":1173,"value":"mutable \nrouletteLossCount = 0","pinned":false,"mode":"js","data":null,"name":null},{"id":1210,"value":"md`If you hit that button enough times, you'll see that the losses have a significant margin over the wins.\n\nBut that's okay - there's still a significant chance the casino loses money, right? 🤔`","pinned":false,"mode":"js","data":null,"name":null},{"id":1214,"value":"md`### A day gambling`","pinned":false,"mode":"js","data":null,"name":null},{"id":1217,"value":"md`Let's say we have $0 to start with, and decide to try our luck at roulette. We start by taking on some debt - but do we have a shot at getting rich?`","pinned":false,"mode":"js","data":null,"name":null},{"id":1248,"value":"viewof aDayOfRoulette = html`<button class=\"block accent\">Play a day of Roulette $</button>`","pinned":false,"mode":"js","data":null,"name":null},{"id":1223,"value":"{\n  // Change this!!!\n  const numOfBets = 5;\n\n  aDayOfRoulette;\n  let balance = 0;\n  \n  for(var i = 0; i<numOfBets; i++){ \n   balance-=100;\n   let division = Math.floor(rand(-1,39)) \n   if(division > 0 && division < 19){\n    balance+=200;\n   }\n  }\n  \n  const word =  balance > 0 ? \"gained 🥳\" : \"lost 😞\";\n  return `Money ${word}: $${Math.abs(balance)}`;\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":1280,"value":"md`Huh, from this demo: maybe not a bad idea. It might be possible to get rich 🤔`","pinned":false,"mode":"js","data":null,"name":null},{"id":1283,"value":"md`Now, try changing \\`numOfBets\\` to 100. Then 1000. Then 10000. Keep turning it up, and see how the money you make changes 😮`","pinned":false,"mode":"js","data":null,"name":null},{"id":1294,"value":"md`## The house always wins - and the law of large numbers.`","pinned":false,"mode":"js","data":null,"name":null},{"id":1320,"value":"md`The law of large numbers says that as the number of trials you take increases, the results come closer to the *expected* value.`","pinned":false,"mode":"js","data":null,"name":null},{"id":1324,"value":"md`We saw that as the number of points we plot increased, our accuracy of ${tex`\\pi`} increased - the value of ${tex`\\pi`} we calculated got closer the the *expected* value.`","pinned":false,"mode":"js","data":null,"name":null},{"id":1334,"value":"md`The same applies for roulette: even though there’s a shot of making some money when you play a few times - the odds are very clearly stacked against you. As the number of bets you make increases, your takeaway comes closer to the *expected* value: a loss.`","pinned":false,"mode":"js","data":null,"name":null},{"id":1339,"value":"md`The law of large numbers is the reason the Monte Carlo method is so useful. Measuring random values seems like a very arbitrary thing to do - but doing it a lot of times can turn out to be quite sensible.`","pinned":false,"mode":"js","data":null,"name":null},{"id":1381,"value":"md`Try this out for yourself - even without a computer.\n\nJust toss a coin and plot a graph - with the number of tosses on the *x* axis, and the % of heads on the *y* axis - as you move towards the right, your *y* axis will come closer to 50%.`","pinned":false,"mode":"js","data":null,"name":null},{"id":1677,"value":"viewof tossInputs = {\n  let a = html`<button class=\"block inline accent\" style=\"padding: 5px\">Toss coin</button>`;\n  a.onclick = () => mutable tossCoin = 1;\n  let b = html`<button class=\"block inline\" style=\"padding: 5px\">Reset</button>`\n  b.onclick = () => {mutable heads = 0; mutable tosses = 0; mutable outcomes = []}\n  return html`${a} ${b}`;\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":1570,"value":"{\n  tossCoin;\n  let outcome = rand(-1,1);\n  mutable tosses+=1;\n  \n  if(outcome > 0) {\n    mutable heads+=1;\n  }\n  \n  mutable outcomes = [...mutable outcomes, {\n    ratio: mutable heads/ mutable tosses,\n    heads: mutable heads,\n    tosses: mutable tosses\n  }]\n\n  return outcome > 0 ? '🔴 Heads' : '🔵 Tails'\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":1727,"value":"{\n  const graph = vl.markLine().data(outcomes).encode(\n    vl.x().fieldQ('tosses').title('No. of tosses'),\n    vl.y().fieldQ('ratio').title('Ratio of heads')  );\n  const point = vl.markCircle().data(outcomes).encode(\n    vl.x().fieldQ('tosses'),\n    vl.y().fieldQ('ratio'),\n    vl.tooltip(['tosses', 'heads', 'ratio'])\n  );\n  \n  return vl.layer(graph, point).render();\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":1683,"value":"mutable heads = 0;","pinned":false,"mode":"js","data":null,"name":null},{"id":1685,"value":"mutable tosses = 0;","pinned":false,"mode":"js","data":null,"name":null},{"id":1776,"value":"md`## That's it!`","pinned":false,"mode":"js","data":null,"name":null},{"id":1781,"value":"md`It was a lot of fun to build this explorable essay: and I learned a ton. This is the first in a series of essays where I'll explore interesting ideas in math and computer science - I think learning in these fields can get a bit too theoretical sometimes, and explorable explanations can be useful because of the experimentation they allow.` ","pinned":false,"mode":"js","data":null,"name":null},{"id":1787,"value":"md`If you'd like to get an email when I publish a new essay, you can sign up for updates on [buttondown.email/essays](https://buttondown.email/essays).`","pinned":false,"mode":"js","data":null,"name":null},{"id":1794,"value":"md`If you enjoyed reading and playing around with this, please consider buying me a book on [read.gift/u/jajoosam](https://read.gift/u/jajoosam) - it'd go a long way in helping me learn more and keep me motivated.`","pinned":false,"mode":"js","data":null,"name":null},{"id":1800,"value":"md`### References`","pinned":false,"mode":"js","data":null,"name":null},{"id":1806,"value":"md`\n- [John Guttag's lecture on Monte Carlo Simulations](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0002-introduction-to-computational-thinking-and-data-science-fall-2016/lecture-videos/lecture-6-monte-carlo-simulation/)\n- [Calculating Pi with Darts, Physics Girl and Veritasium](https://www.youtube.com/watch?v=M34TO71SKGk)\n- [What is Monte Carlo, LeisOS](https://www.youtube.com/watch?v=AyBNnkYrSWY)\n- [Monte Carlo methods - Why it's a bad idea to go to the casino](https://easylang.online/apps/tutorial_mcarlo.html)\n- [Monte Carlo integration on Algorithm Archive](https://www.algorithm-archive.org/contents/monte_carlo_integration/monte_carlo_integration.html)\n- [Monte Carlo Casino on Wikipedia](https://en.wikipedia.org/wiki/Monte_Carlo_Casino)\n`","pinned":false,"mode":"js","data":null,"name":null},{"id":1816,"value":"md`Thank you Zachary Steinberg, Amit Patel, Tyler Cowen, Philipp Wacker and Aashish Ium for feedback of drafts of this essay.`","pinned":false,"mode":"js","data":null,"name":null},{"id":135,"value":"md`### Appendix`","pinned":false,"mode":"js","data":null,"name":null},{"id":72,"value":"md`*All of these are dependencies/non important setup for this essay.*`","pinned":false,"mode":"js","data":null,"name":null},{"id":555,"value":"import {vl} from '@vega/vega-lite-api'","pinned":false,"mode":"js","data":null,"name":null},{"id":558,"value":"import {printTable} from '@uwdata/data-utilities'","pinned":false,"mode":"js","data":null,"name":null},{"id":2,"value":"Two = require(\"https://cdnjs.cloudflare.com/ajax/libs/two.js/0.7.0-beta.3/two.min.js\")","pinned":false,"mode":"js","data":null,"name":null},{"id":41,"value":"two = {\n  let graphics = new Two({width: Math.min(window.innerWidth*0.9, 500), height:  Math.min(window.innerWidth*0.9, 500)}).appendTo(shape); \n  return graphics;\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":148,"value":"import {button, number} from \"@jashkenas/inputs\"","pinned":false,"mode":"js","data":null,"name":null},{"id":586,"value":"function rand(min, max) {\n    return Math.random() * (max - min) + min;\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":591,"value":"mutable graph = {\n  const url = `https://cdnjs.cloudflare.com/ajax/libs/jsxgraph/0.99.7/jsxgraphcore.js`;\n  const graph = await require(url).catch(() => window.JXG);\n  const board = graph.JSXGraph.initBoard('graph', { \n    boundingbox: [-4, 10, 4 ,0], axis:true,\n  });\n  return board\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":671,"value":"mean = (arr) => {\n  let sum = 0\n  arr.forEach(e=>sum+=e);\n  return sum/arr.length;\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":687,"value":"deviation = (arr) => {\n  const avg = mean(arr);\n  let sq = 0;\n  arr.forEach(e=>{\n    sq+=Math.pow(e-avg, 2)\n  })\n  return (Math.sqrt(sq/arr.length));\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":722,"value":"mutable piData = [];","pinned":false,"mode":"js","data":null,"name":null},{"id":750,"value":"plot = (stuff, x, y, z) => {\n  if(z){\n  const point = vl.markCircle().data(stuff).encode(\n    vl.x().fieldQ(x.key),\n    vl.y().fieldQ(y.key),\n    vl.tooltip(['count', 'deviation', 'error', 'mean'])\n  );\n  return point.render()\n  }\n  const graph = vl.markLine().data(stuff).encode(\n    vl.x().fieldQ(x.key).title(x.title),\n    vl.y().fieldQ(y.key).title(y.title),  );\n  const point = vl.markCircle().data(stuff).encode(\n    vl.x().fieldQ(x.key),\n    vl.y().fieldQ(y.key),\n    vl.tooltip(['count', 'deviation', 'error', 'mean'])\n  );\n  \n  return vl.layer(graph, point).render();\n}","pinned":false,"mode":"js","data":null,"name":null},{"id":953,"value":"mutable go = 0;","pinned":false,"mode":"js","data":null,"name":null},{"id":1390,"value":"mutable toAddCircle = 5;","pinned":false,"mode":"js","data":null,"name":null},{"id":1406,"value":"mutable toAddGraph = 0;","pinned":false,"mode":"js","data":null,"name":null},{"id":1689,"value":"mutable outcomes = [];","pinned":false,"mode":"js","data":null,"name":null},{"id":1732,"value":"mutable tossCoin = 0;","pinned":false,"mode":"js","data":null,"name":null},{"id":1417,"value":"html`<link rel=\"stylesheet\" href=\"https://unpkg.com/blocks.css/dist/blocks.min.css\" />`","pinned":false,"mode":"js","data":null,"name":null},{"id":1636,"value":"html`\n<style>\n@import url('https://fonts.googleapis.com/css?family=Anonymous+Pro|Roboto&display=swap');\np{\n  font-family: 'Roboto', monospace;\n}\nh1,h2,h3,h4{\n  font-family: 'Anonymous Pro', monospace;\n}\n\nh1{\n background: -webkit-linear-gradient(#59C173, #a17fe0);\n  -webkit-background-clip: text;\n  -webkit-text-fill-color: transparent;\n  font-size: 3em;\n}\n\nh2{\n  color: #FF7473;\n  font-size: 2em;\n}\n\nh3{\n  color: #3a5ec5;\n  font-size: 1.5em;\n}\n\nstrong{\n  color: #85144b;\n}\n\n</style>\n`","pinned":false,"mode":"js","data":null,"name":null},{"id":1508,"value":"html`<style>.circ > svg{display:block}</style>`","pinned":false,"mode":"js","data":null,"name":null},{"id":1827,"value":"{\n  // hits counter\n  return html`<img src=\"https://beautiful-ocarina.glitch.me/counter.png?fallback=MY_WEBSITE&color=black\" alt=\"\" style=\"vertical-align: bottom;\" aria-hidden=\"true\">`\n}","pinned":false,"mode":"js","data":null,"name":null}],"resolutions":[],"schedule":null,"last_view_time":null}