<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Varad Kulkarni on Medium]]></title>
        <description><![CDATA[Stories by Varad Kulkarni on Medium]]></description>
        <link>https://medium.com/@varadkulk123?source=rss-4e436bf8080c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RI3EsV_AVwH-Hmvn</url>
            <title>Stories by Varad Kulkarni on Medium</title>
            <link>https://medium.com/@varadkulk123?source=rss-4e436bf8080c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:47:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@varadkulk123/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Methods of Approximating Pi]]></title>
            <link>https://medium.com/@varadkulk123/methods-of-approximating-pi-d61fcb042ad1?source=rss-4e436bf8080c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d61fcb042ad1</guid>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[pi]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[approximation]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Varad Kulkarni]]></dc:creator>
            <pubDate>Fri, 19 May 2023 15:41:24 GMT</pubDate>
            <atom:updated>2023-05-19T15:41:24.159Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hGCZwnJTbGFpjjoB" /><figcaption>Photo by <a href="https://unsplash.com/fr/@starburst1977?utm_source=medium&amp;utm_medium=referral">Sven Read</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>All code in this essay can be found <a href="https://github.com/VaradK62442/piApproximations">here</a>.</h4><h3>Introduction</h3><p>The constant pi is perhaps the most famous mathematical symbol, being used in several areas, from topology to fluid dynamics. Since around 1900 BC, pi has been approximated to varying degrees of accuracy, getting up to 38 correct digits in the year 1630 with Austrian astronomer Christoph Grienberger by using a 10⁴⁰ sided polygon to approximate the value.</p><p>As the modern age of computers approached, the urge for humanity to calculate more and more digits of pi become stronger, with 1 million digits calculated in 1973.</p><p>This has lead to several methods of approximating pi with infinite sums, randomness, and other ways being discovered. In this essay, I will go through 5 such methods:</p><ul><li>the Madhava-Liebniz formula,</li><li>the Wallis product,</li><li>Newton’s sum,</li><li>Buffon’s needle,</li><li>and the Monte Carlo method.</li></ul><p>Buffon’s needle and the Monte Carlo method rely on randomness to approximate pi, whereas the other 3 methods use an infinite series.</p><h3>The Madhava-Liebniz Formula</h3><p>The Madhava-Liebniz formula for pi states that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*VzWR3il6-0BLvd1fPSum4Q.png" /></figure><p>By multiplying the left hand side by 4, we can get an approximation for pi.</p><p>The derivation of this formula comes from the Taylor expansion of the arctan function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*QA0xFNZeIQg_YmRQM1Wu2Q.png" /></figure><p>We know that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*M_ZHbe5PpSyMEkvo3qwJbA.png" /></figure><p>so it follows that substituting x = 1 into the Taylor expansion for arctan gives us the Madhava-Liebniz formula.</p><p>This formula gets its name from the Indian mathematician Madhava of Sangamagrama who discovered this formula in the 14th to 15th century, and was later discovered independently by James Gregory in 1671 and then again independently by Gottfried Liebniz in 1673. This formula is also sometimes called the Madhava-Gregory-Liebniz formula, or just the Liebniz formula.</p><p>We can write some code to approximate pi using this formula, up to a specified point. We will define a function pi_approx(n) which takes in a parameter n that specifies how many iterations to run.</p><p>We will keep a running total in the variable approximation and we will initialise an empty dictionary values to store our results in at each iteration. This will be helpful to plot our results.</p><p>The function itself is quite simple — we run a for loop the specified number of times, each time add or subtracting the term from the running total. We calculate this term by firstly raising -1 to the power of i, our iterating variable. This gives us alternating negative and positive terms.</p><p>We then multiply this by the reciprocal of odd numbers, found by calculating 2 * i — 1, and then multiply this result by 4, since we want pi, and the formula will give us pi/4.</p><pre># function to approximate pi by using madhava-liebniz approximation<br>def pi_approx(n):<br>    # running total<br>    approximation = 0<br>    values = {}<br><br>    # repeat from 1 to n<br>    for i in range(1, n+1):<br>        # add alternating negative and positive values<br>        # multiplied by reciprocal of odd numbers<br>        # multipled by 4<br>        approximation += (-1)**(i+1) * (1 / (2*i-1)) * 4<br>        values[i] = approximation<br><br>    return values</pre><p>We can now use the matplotlib library to plot our results. We will define the function plot(n) to do this, the parameter n being the value passed into our pi_approx function. We will also plot the differences between our approximation and pi at each stage, and also print out the final approximation that was achieved by this method.</p><pre># function to plot results, and pi constant<br># also plot differences from predicted value to pi<br>def plot(n):<br>    # create dict of pi approximated values<br>    approximations = pi_approx(n)<br>    differences = [abs(val - pi) for val in approximations.values()]<br><br>    # plot values<br>    plt.plot(approximations.keys(), approximations.values())<br>    # plot pi constant<br>    plt.plot([0, n], [pi, pi])<br>    # plot differences<br>    plt.plot(approximations.keys(), differences)<br><br>    print(f&#39;&#39;&#39;<br>    Pi: {pi}<br>    Final approximation: {approximations[n]}<br>    Final difference: {differences[-1]}<br>    &#39;&#39;&#39;)<br><br>    plt.show()</pre><p>Running this plot function 1,000,000 times gives us the following results.</p><p>The final approximation using this method was 3.1415916535897743. This has a difference of around 1e-06 from the actual value of pi. The graphs for the approximation produced by this are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*02oWlbl0YX8AUG9a-3SKyQ.png" /></figure><p>As you can see, this isn’t very interesting. The orange line represents the actual value of pi, and the blue line is our approximation. You can see that it deviates a lot at the start, but very quickly falls down to near the actual value of pi. If we zoom in to the start of the graph, we see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qtv26Y8HB9wHrfgKKIHf3Q.png" /></figure><p>You can see that the approximation oscillates from above and below the actual value, with the difference between the two decreasing. By zooming in to the end of the graph, we see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zyyj7LSi9ObhO9BOqeJ48g.png" /></figure><p>You can see that the value is still oscillating, with minimal difference, and as we increase the number of repetitions, this difference will go towards 0.</p><p>Here is the graph of the differences produced by the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*islAmyeeFRGZc8VP5t0k7Q.png" /></figure><p>Again, not very interesting. There is a large difference at the start, but this quickly falls down to near zero, as we saw in the previous graph. If we zoom in to the start of the graph, we see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x71z446_G7YWi4fGmoYOxg.png" /></figure><p>We can see a very smooth, almost logarithmic decline in the difference between our approximation and the value of pi.</p><h3>The Wallis product</h3><p>The Wallis product, discovered by John Wallis in 1656 states that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*tb_26rPNx3PByCNwSRNJMg.png" /></figure><p>We can multiply the right hand side to get a value for pi. The proof for this is quite long, so I won’t go into it in this essay. Instead, let’s get straight into writing code for this so we can perform a similar experiment as we did for the Madhava-Liebniz method.</p><p>We will again define a pi_approx(n) method to calculate this product up to n iterations. We will also again keep a running total in the approximations variable, and an empty values dictionary to store our results.</p><p>At each iteration, we multiply our variable by 2*i / (2*i — 1) and then again multiply it by 2*i / (2*i + 1), before finally multiplying it by 2, and storing it in the values dictionary.</p><pre># function to approximate pi using wallis product method<br>def pi_approx(n):<br>    # running total<br>    approximation = 1<br>    values = {}<br><br>    for i in range(1, n+1):<br>        # multiply by 2*i / (2*i - 1) and by 2*i / (2*i + 1)<br>        approximation *= (2*i / (2*i - 1))<br>        approximation *= (2*i / (2*i + 1))<br>        values[i] = approximation * 2<br><br>    return values</pre><p>We again make a similar plot function to plot these results.</p><pre># function to plot results, and pi constant<br># also plot differences from predicted value to pi<br>def plot(n):<br>    approximations = pi_approx(n)<br>    differences = [abs(val - pi) for val in approximations.values()]<br><br>    plt.figure(1)<br>    plt.suptitle(&quot;Approximation&quot;)<br>    # plot values<br>    plt.plot(approximations.keys(), approximations.values())<br>    # plot pi constant<br>    plt.plot([0, n], [pi, pi])<br><br>    plt.figure(2)<br>    plt.suptitle(&quot;Differences&quot;)<br>    # plot differences<br>    plt.plot(approximations.keys(), differences)<br><br>    print(f&#39;&#39;&#39;<br>    Pi: {pi}<br>    Final approximation: {approximations[n]}<br>    Final difference: {differences[-1]}<br>    &#39;&#39;&#39;)<br><br>    plt.show()</pre><p>Here are the results we get when we run this function 1,000,000 times.</p><p>The final approximation for pi with the Wallis product method is 3.1415918681915005. This has a difference of around 7.8e-07, which is much less than the Madhava-Liebniz method, making this a better method for approximating pi.</p><p>Here is the graph of approximations produced:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Am_AYZGAsLX4qzfwVzHcaQ.png" /></figure><p>Not very interesting, but different to the Madhava-Liebniz method since it does not oscillate above and below the value of pi, and instead approaches it from the bottom. Here is what the graph looks like when we zoom into the start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5mu8gdYDsj5sF4KD_Bomlg.png" /></figure><p>You can see that there is a very smooth, almost logarithmic increase towards the actual value of pi, as the approximation approaches it.</p><p>Here is the graph of differences with the Wallis product method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xVLyzegBmc-yy_dPx7-hw.png" /></figure><p>Again, not very interesting, but very similar to the Madhava-Liebniz method in that it starts very high but quickly drops down to near zero. Zooming in to the start, we can again see that almost logarithmic decrease:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLyel3tWD1MDkAFTt2FPMA.png" /></figure><h3>Newton’s Sum</h3><p>Now onto our last infinte series for approximating pi. Newton’s Sum states that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*7D7ZyLUbEk2RMMEsBUcXeg.png" /></figure><p>Hence, multiplying the right hand side by 2sqrt(2) gives us a value for pi.</p><p>Again, let’s write the pi_approx and plot functions for this method.</p><pre># function to approximate pi by using newton&#39;s sum method<br>def pi_approx(n):<br>    # running total<br>    approximation = 0<br>    values = {}<br><br>    # repeat from 1 to n<br>    for i in range(0, n+1):<br>        # apply summation mentioned above<br>        # alternating positive and negative values<br>        # multiply by 2sqrt(2)<br>        approximation += (-1)**i * ((1/(4*i+1)) + (1/(4*i+3)))<br>        values[i] = approximation * 2 * sqrt(2)<br><br>    return values</pre><pre># function to plot results, and pi constant<br># also plot differences from predicted value to pi<br>def plot(n):<br>    # create dict of pi approximated values<br>    approximations = pi_approx(n)<br>    differences = [abs(val - pi) for val in approximations.values()]<br><br>    plt.figure(1)<br>    plt.suptitle(&quot;Approximations&quot;)<br>    # plot values<br>    plt.plot(approximations.keys(), approximations.values())<br>    # plot pi constant<br>    plt.plot([0, n], [pi, pi])<br><br>    plt.figure(2)<br>    plt.suptitle(&quot;Differences&quot;)<br>    # plot differences<br>    plt.plot(approximations.keys(), differences)<br><br>    print(f&#39;&#39;&#39;<br>    Pi: {pi}<br>    Final approximation: {approximations[n]}<br>    Final difference: {differences[-1]}<br>    &#39;&#39;&#39;)<br><br>    plt.show()</pre><p>Running this 1,000,000 times, we get a final approximation for pi to be 3.1415933606960103. This has a difference of around 7e-07 from the actual value of pi, making this method slightly better than the Wallis product.</p><p>Here is the graph of approximations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCsPX-ThulIhvjXcG2-iAg.png" /></figure><p>Quite similar to the Madhava-Liebniz method, which makes sense since we are once again alternating between adding and subtracting terms. We can once again zoom in to see the oscillation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B0GDuXZN8Wv8rxCnVsvt3g.png" /></figure><p>The graph of differences is very similar to the previous two methods, with an almost logarithmic decrease towards zero.</p><h3>Buffon’s needle</h3><p>Now onto the first of our algorithms that uses randomness. The Buffon’s needle problem considers the probability of dropping a needle onto a floor with parallel strips of wood, and having it land on an edge. This probability was found to be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*8QAS08-N8z6apaXsrJnZ2A.png" /></figure><p>where p is the probability, l is the length of the needle, and t is the width of a plank of wood. By rearranging this equation for pi, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/84/1*MjOx-OhSzO8jO9LRW-7tqw.png" /></figure><p>The probability that a needle lands on an edge can be expressed as the ratio of needles that land on an edge to the total number of needles dropped. Let h represent the number of needles that land on an edge, and n be the total number of needles dropped. Hence, our formula for pi becomes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/97/1*F4r-Izey_kTL_5Om2zPtMw.png" /></figure><p>Using code, we can define values for l and t, simulate dropping needles, keep track of how many are dropped and how many land on an edge, and hence find an approximation for pi using all of these values.</p><p>The method we will use is as follows:</p><ul><li>Draw imaginary vertical lines representing boundaries of planks of wood, 5 units apart. Hence, t = 5.</li><li>Pick a random point on the canvas, and then pick a random poin that is 2.6 units away from it. Hence, l = 2.5.</li><li>Check if this line (needle) crosses any boundary line. If it does, increment our counter for h.</li></ul><p>We will define a function pi_approx that takes in the following parameters:</p><ul><li>reps — how many repetitions to perform, i.e. how many needles to drop</li><li>x_bound — the x coordinate of the end of our canvas</li><li>y_bound — the y coordinate of the end of our canvas</li><li>t — the value for how far apart our planks are, t</li><li>l — the value for how long our needles are, l</li></ul><p>We first initalise n and h to be 0. We also create a results list to keep track of our results.</p><p>We then start a for loop. We first pick x and y coordinates using the random.uniform function. We pick numbers from 0 to x_bound for the x coordinate, and numbers from 0 to y_bound for the y coordinate.</p><p>We then pick a random angle. This will be the angle that our needle falls at. We then use trigonometry, and this angle to calculate our second pair of x,y coordinates.</p><pre># function to approximate pi using Buffon&#39;s needle method<br>def pi_approx(reps, x_bound, y_bound, t, l):<br>    n, h = 0, 0<br>    <br>    # list for storing results<br>    results = []<br><br>    for _ in range(reps):<br>        # pick random x and y coordinate<br>        x_1, y_1 = (random.uniform(0, x_bound), random.uniform(0, y_bound))<br><br>        # pick second random x and y coordinate<br>        # such that the distance between the first set of points <br>        # and this one is equal to l<br><br>        # first, we pick a random angle for the line to follow<br>        # and convert this into radians<br>        theta = radians(random.uniform(0,360))<br><br>        # using trigonometry, we add the respective values <br>        # to the first x and y coordinates<br>        # to get the second x y coordinates<br>        x_2 = (x_1 + cos(theta) * l)<br>        y_2 = (y_1 + sin(theta) * l)</pre><p>Now, we need to check if the needle is lying on a boundary. We can do this by checking if there is a multiple of t within our x coordinates. To do this, we divide the x coordinates by t, and check if there is an integer between that range. If there is, the needle crosses a boundary.</p><p>For example, if the needle has its first x coordinate at 14.5, and its second coordinate at 18, then dividing those values by t = 5 gives 2.9 and 3.6. Since there is an integer, 3, between these two values, we know that the needle crosses a boundary, and we can increment h.</p><pre>        lower_bound = x_1 / t<br>        upper_bound = x_2 / t<br><br>        if abs(floor(upper_bound) - floor(lower_bound)) == 1:<br>            # if the needle is on a boundary, increment h<br>            h += 1<br>            crosses_line = True<br>        else:<br>            crosses_line = False<br><br>        # increment n no matter what<br>        n += 1</pre><p>We now have all the values necessary to calculate a value for our approximation, and can add all the data to our results list.</p><pre>        try:<br>            approximation = (2 * l * n) / (t * h)<br>        except ZeroDivisionError:<br>            approximation = None<br><br>        results.append({<br>            &#39;x_1&#39;: x_1,<br>            &#39;y_1&#39;: y_1,<br>            &#39;x_2&#39;: x_2,<br>            &#39;y_2&#39;: y_2,<br>            &#39;n&#39;: n,<br>            &#39;h&#39;: h,<br>            &#39;approximation&#39;: approximation,<br>            &#39;probability&#39;: h / n,<br>            &#39;cross&#39;: crosses_line<br>        })<br><br>    return results</pre><p>If h is equal to 0, we need to check that since dividing by h would cause an error. If h is equal to 0, then we just set our approximation for that iteration to be None.</p><p>We can now create a function to plot all of these results. We want to plot 2 things — where the needles landed, and a graph of our approximation against pi.</p><pre># function to plot both needle drops and estimation results<br>def plot(results, x_bound, y_bound, t, l):<br>    plt.figure(1)<br>    plt.suptitle(&quot;Needle drops&quot;)<br>    # plot boundary lines<br>    for i in range(x_bound):<br>        if i % t == 0:<br>            plt.plot((i, i), (0, y_bound), &#39;k-&#39;)<br><br>    # plot needles<br>    for needle in results:<br>        if needle[&quot;cross&quot;]:<br>            col = &#39;g&#39;<br>        else:<br>            col = &#39;r&#39;<br><br>        plt.plot((needle[&#39;x_1&#39;], needle[&#39;x_2&#39;]), <br>                 (needle[&#39;y_1&#39;], needle[&#39;y_2&#39;]), col)<br><br>    # plot results<br>    plt.figure(2)<br>    plt.suptitle(&quot;Approximation&quot;)<br>    plt.plot([needle[&#39;n&#39;] for needle in results], <br>             [needle[&quot;approximation&quot;] for needle in results])<br>    plt.plot((0, len(results)), (pi, pi))<br><br>    plt.show()</pre><p>Running this function 1,000,000 gives a final approximation for pi to be 3.1459192285238076. This has a difference of around 0.004 from pi. Note that, since this algorithm is heavily dependent on randomness, this result will be different each time. Also note that this difference is much greater than the infinite series methods.</p><p>Unfortunately, my computer cannot handle graphing the results for 1,000,000 iterations, so instead here is the results for 10,000 iterations, with x and y bounds being set to 2,000, the width of a plank being 5, and the length of a needle being 2.6:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPrQ963UFnG75P7i5SW4Lg.png" /></figure><p>The entire graph is very overwhelming and not clear, so here is a section of it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FtVe2kjuKgv29az7own5ZA.png" /></figure><p>You can see the individual needles are coloured green if they cross a boundary, and red otherwise.</p><p>Here is the graph of the approximation against pi:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dnnJh1NUEa85zQso0zavA.png" /></figure><p>This is quite an interesting graph. Of course, this will be different each time the program is run. The random nature of the program is evident in this graph, as you can see the approximation sporadically moving up and down.</p><h3>Monte Carlo</h3><p>Last but not least, we arrive at the Monte Carlo method. This is perhaps the most famous method of approximating pi using randomness, and the method itself is quite simple.</p><p>Consider a square with length 2, and a circle inscribed within the square. The radius of this circle will be 1. The area of the circle will be pi, and the area of the square will be 4. Hence, the ratio between the two areas will be pi/4. Using this fact, we can generate random points inside the square, and check if they land inside the circle or not. The ratio of points inside the circle and the total number of points will approach pi/4 since, as the number of points increases, it will better and better approximate the area of the shapes.</p><p>We again define the pi_approx(n) function and create an empty list called results to store our results, and initialise 3 variables as 0:</p><ul><li>inside to keep track of points that land inside the circle</li><li>outside to keep track of points that land outside the circle</li><li>total to keep track of total number of points</li></ul><p>We then start a for loop. Inside the loop, we randomly choose two points between -1 and 1 for the x and y coordinate of our point. We then check if this point is within the circle by calculating its distance from the centre, and checking whether this is less than or equal to 1. If it is less than or equal to 1, then it is within the circle. We then find an approximation by calculating (inside / total) * 4, and then add all of this data to our results list.</p><pre>def pi_approx(n):<br>    results = []<br>    <br>    # initialise counters<br>    inside, outside, total = 0, 0, 0<br><br>    for _ in range(n):<br>        # square has coordinates from (-1, -1) to (1, 1)<br>        # pick random point<br>        x, y = random.uniform(-1, 1), random.uniform(-1, 1)<br><br>        # check if point is inside circle<br>        # we can do this by checking if <br>        # the distance of the point from the origin is<br>        # more or less than 1<br>        dist = sqrt(x**2 + y**2)<br><br>        if abs(dist) &gt; 1:<br>            # point is outside the circle<br>            outside += 1<br>            in_circle = False<br>        else:<br>            # point is inside the circle<br>            inside += 1<br>            in_circle = True<br><br>        total += 1<br><br>        try:<br>            approximation = (inside / total) * 4<br>        except ZeroDivisionError:<br>            approximation = 0<br><br>        results.append({<br>            &#39;x&#39;: x,<br>            &#39;y&#39;: y,<br>            &#39;inside&#39;: inside,<br>            &#39;outside&#39;: outside,<br>            &#39;total&#39;: total,<br>            &#39;approximation&#39;: approximation,<br>            &#39;in_circle&#39;: in_circle,<br>        })<br><br>    return results</pre><p>We can define a plot(n) function to plot these results. We can plot the actual points and a graph of our approximation agains the value of pi.</p><pre>def plot(results):<br>    plt.figure(1)<br>    plt.suptitle(&quot;Points&quot;)<br>    # plot points<br>    for point in results:<br>        if point[&#39;in_circle&#39;]:<br>            c = &#39;g&#39;<br>        else:<br>            c = &#39;r&#39;<br>    <br>        plt.scatter(point[&#39;x&#39;], point[&#39;y&#39;], c=c, s=3)<br>            <br>    # plot results<br>    plt.figure(2)<br>    plt.suptitle(&quot;Approximations&quot;)<br>    plt.plot([point[&#39;total&#39;] for point in results], <br>             [point[&quot;approximation&quot;] for point in results])<br>    plt.plot((0, len(results)), (pi, pi))<br><br>    plt.show()</pre><p>Running this code 1,000,000 times gives us the final approximation for pi to be 3.141984. This has a difference of around 0.0004 from pi. Again, this value will be different each time the program is ran since the algorithm relies so heavily on randomness.</p><p>Here is the graph generated by repeating this code 1,000 times, since 1,000,000 repetitions is too much for my computer to handle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*nk6EuYn9oub9iysfBNGJcg.png" /></figure><p>You can see the clear circle traced out by the points, since green points signify the point being inside the circle, and red points signify the points being outside the circle.</p><p>Here is the graph of approximation against pi:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ssgj1ySYYcQFXneOdziBqg.png" /></figure><p>Since there are only 1,000 iteration, you can clearly see each approximation. The graph has a similar chaotic property to the Buffon’s needle graph, in that it sproadically jumps up and down, while still approaching pi.</p><h3>Conclusion</h3><p>Here is a summarised table of results of all 5 method we have gone through, for 1,000,000 repetitions:</p><pre>+-------------------+-----------------------+--------------------+<br>|      Method       |  Final approximation  |  Final difference  |<br>+-------------------+-----------------------+--------------------+<br>| Madhava-Liebniz   |  3.1415916535897743   |  1.00000001879e-06 |<br>| Wallis Product    |  3.1415918681915005   |  7.85398292624e-07 |<br>| Newton&#39;s Sum      |  3.1415933606960103   |  7.07106217135e-07 |<br>| Buffon&#39;s Needle   |  3.1459192285238076*  |  0.00432657493*    |<br>| Monte Carlo       |  3.141984*            |  0.00039134641*    |<br>+-------------------+-----------------------+--------------------+</pre><p>The “*” indicates that the method is random, and the results will vary each time the program is ran.</p><p>In conclusion, the Newton’s sum method has the lest final difference, with the Wallis product as a close second. The Madhava-Liebniz is the most impressive to me, to have been discovered so early when such a concrete understanding of calculus was required is brilliant.</p><p>The two randomised methods have the highest error, which is to be expected. Maybe running them for 1 billion iterations will provide a result that is comparable to the methods that use infinite series.</p><p>There are several other methods to approximate pi, and they all have very interesting proofs. Even the proofs for the three infinite series methods used in this essay are very interesting, and it’s amazing that these were discovered so early on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d61fcb042ad1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Analysis of Resource Dsitribution in Catan]]></title>
            <link>https://medium.com/@varadkulk123/an-analysis-of-resource-dsitribution-in-catan-d8d91b518e71?source=rss-4e436bf8080c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8d91b518e71</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[catan]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[board-games]]></category>
            <category><![CDATA[probability]]></category>
            <dc:creator><![CDATA[Varad Kulkarni]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 20:22:47 GMT</pubDate>
            <atom:updated>2023-04-02T20:37:59.316Z</atom:updated>
            <content:encoded><![CDATA[<h3>An Analysis of Resource Distribution in Catan</h3><h4>All code in this essay can be found <a href="https://github.com/VaradK62442/CatanSim">here</a>.</h4><h3><strong>Introduction</strong></h3><p>The Settler’s of Catan is a fantastic board game that I was introduced to recently. In the game, players compete to obtain resources and build their settlement while trading against other players. The duality of both competing and cooperating with other players makes the game theory behind the game very interesting.</p><p>Since playing the game, I have wanted to write about the game, and I decided to start with a simple analysis of how frequently resources are generated. To do this, I created a program to simulate millions of games. Before we get into code, here is an explanation on how resources are generated in Catan.</p><h3>Resource generation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7527mezf4ogUu-Cj.jpg" /><figcaption>An example of a Catan board</figcaption></figure><p>Catan is played on a board based on hexagonal tiles, as shown above. Each tile generates a different resource based on the art on the tile. The resources are</p><ul><li>Wheat</li><li>Ore</li><li>Sheep</li><li>Wood</li><li>Brick</li></ul><p>There are 3 brick and ore tiles, 4 wheat, sheep, and wood tiles, and 1 desert tile. The desert tile does not generate resources, and instead houses the robber at the start of the game.</p><p>On each player’s turn, they roll 2 dice, and the total of the dice dictates which resource is generated. Each resource has a token on it corresponding to what roll generates that resource. For example, if a “4” token was on a sheep tile, a sheep resource is generated each time a 4 is rolled (if a player has a building on that tile).</p><p>The rulebook recommends a beginner’s setup for players who are playing for the first time, and has some rules on how to generate random boards for different board layouts. To set up the board, tiles should be placed randomly, and the tokens should be laid out in a specific order, going from the top left of the board and moving anti-clockwise in a spiral, skipping over the desert. This should guarantee a balanced and even set up for the game.</p><h3>Generating the board</h3><p>We will be using Python to simulate games, and the Python modules tkinter and matplotlib to visualise the data.</p><p>First, we create the code to randomly generate the board. A board in Catan has 5 rows with 3 tiles in the first row, 4 in the second, 5 in the third, 4 in the fourth, and 3 in the fifth. This creates the full board shape.</p><p>To represent each tile, we create a class called Tile with two attributes — type, and token. The type attribute represents what kind of resource the tile generates, and the token attribute represents what number needs to be rolled to generate that tile’s resource.</p><p>For the desert, the type will be “desert” and the token for that tile will be 7 since, in the game, the robber is activated when a 7 is rolled.</p><p>We define a class in the standard way in Python:</p><pre>class Tile:<br>    def __init__(self, type, token):<br>        self.type = type<br>        self.token = token</pre><p>We now create a board variable, that we initialise as an empty list, and we also create a list of possible tiles to be chosen from, so that we can randomly choose a tile from that list.</p><pre>board = []<br>tiles = [&#39;desert&#39;] + [&#39;wheat&#39;]*4 + [&#39;sheep&#39;]*4 + <br>        [&#39;wood&#39;]*4 + [&#39;brick&#39;]*3 + [&#39;ore&#39;]*3</pre><p>We can now randomly generate the tiles. We run a fixed loop 5 times, one for each row. If the iteration is the first or the last, we only choose 3 tiles. If the iteration is the second or the second-last, we choose 4 tiles. Otherwise, we choose 5 tiles, since that will be the middle row. We append an empty list to the board variable to add tiles to when we randomly generate them.</p><p>To choose a tile, we choose a random tile type from the tiles list, create an instance of the Tile object with the chosen tile type, and 7 as a default token value. We then append this to the list that we added to the board variable at the start of the loop. We then remove the chosen tile type from the tiles list, so that we get the correct number of each tile.</p><pre>for i in range(5):<br>    board.append([])<br>    if i == 0 or i == 4:<br>        for _ in range(3):<br>            tile_choice = random.choice(tiles)<br>            tile = Tile(tile_choice, 7)<br>            board[i].append(tile)<br>            tiles.remove(tile_choice)<br>    elif i == 1 or i == 3:<br>        for _ in range(4):<br>            tile_choice = random.choice(tiles)<br>            tile = Tile(tile_choice, 7)<br>            board[i].append(tile)<br>            tiles.remove(tile_choice)<br>    else:<br>        for _ in range(5):<br>            tile_choice = random.choice(tiles)<br>            tile = Tile(tile_choice, 7)<br>            board[i].append(tile)<br>            tiles.remove(tile_choice)</pre><p>We can now allocate the tokens to each tile. The rulebook of Catan states the order in which tokens should be allocated. However, this method allocates the tokens in a spiral, which is difficult to do with code. Instead of allocating tokens in this order, we reorder them so that we can allocate them linearly.</p><p>The order in which the rulebook tells the players to allocate them is</p><blockquote>5, 2, 6, 3, 8, 10, 9, 12, 11, 4, 8, 10, 9, 4, 5, 6, 3, 11.</blockquote><p>If we lay out a board, and write down the tokens reading from right to left, we get the order</p><blockquote>5, 10, 8, 2, 9, 11, 4,6, 4, 3, 11, 3, 5, 6, 12, 8, 10, 9.</blockquote><p>We can make a list with the above integers, and allocate them to the tiles in the board. We can allocate them easily by just looping through each item in the board variable (which represents a row), and then looping through each item in that (which represents a tile). We then set the token attribute of each tile to the first element of the tokens list, and we get rid of the first element when we allocate it, by slicing the token list from the second element to the end.</p><p>Before allocating the token, we need to check if the tile type is the desert, and we don’t allocate a token if it is.</p><pre>tokens = [5, 10, 8, 2, 9, 11, 4,6, 4, 3, 11, 3, 5, 6, 12, 8, 10, 9]<br><br>for row in board:<br>    for tile in row:<br>        if tile.type != &quot;desert&quot;:<br>            tile.token = tokens[0]<br>            tokens = tokens[1:]</pre><p>Finally, our board variable is complete.</p><p>We can put all these pieces of code into a function, and return the board variable at the end. We will call this function “gen_board”.</p><h3>Displaying the board</h3><p>After we have generated the board, it would be useful to view what it looks like. To do this, we use Python’s tkinter module, and the Canvas widget within it.</p><p>Without going into too much detail about the boilerplate code of tkinter, we define a main window and a Canvas widget.</p><p>Our goal is to draw the board as hexagons, fill in each tile with a colour corresponding to what type of tile it is, and display the type and token of each tile, within the hexagon.</p><p>Unfortunately, tkinter does not have a function to draw a hexagon, but does have a function to draw polygons. This needs a list of x and y coordinates describing the polygon. We can first define a function to draw a hexagon, and pass in arguments to tell the function where to draw the hexagon, since we want the hexagons to be offset by certain values, to create a full board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*_Kd-svUh6-eYW4WvDWMVcA.png" /></figure><p>We create a list for x and y coordinates, and start with the top corner of the hexagon. The coordinates of this will be 0 for x, and 1 for y. However, the hexagon will be very small on our canvas if the radius of the hexagon is only 1, so we create a variable for the radius of the hexagon, and scale the y coordinate accordingly. Hence, the y coordinate will be r, where “r” is the radius we define.</p><p>The next point we define is the top right corner of the hexagon. To find the coordinates of this, we use a bit of trigonometry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*u3vu1aiiOeIRu328WiyHag.png" /></figure><p>You can see that the red line has an endpoint at the coordinate that we want to draw. The line creates an angle of 30° from the x-axis, and using sine and cosine functions, we can determine the point at which we should draw the polygon at.</p><p>We can form the equation cos(30°) = adjacent / hypotenuse, where the “adjacent” is the length we need to find. cos(30°) is sqrt(3)/2, and the length of the hypotenuse is the radius, r. Therefore, the length of the adjacent side, and hence the x coordinate we should be plotting at, is sqrt(3)*r/2.</p><p>Similarly, we can form the equation sin(30°) = opposite / hypotenuse, where the “opposite” is the length we need to find. sin(30°) is 1/2, the hypotenuse is r, and hence the length of the opposite side, and the y coordinate we should plot at, is r/2.</p><p>We can do the same for all other corners of the hexagon. We get the coordinates:</p><ul><li>(0, r) for the top corner</li><li>(sqrt(3)*r/2, r/2) for the top right corner</li><li>(sqrt(3)*r/2, -r/2) for the bottom right corner</li><li>(0, -r) for the bottom corner</li><li>(-sqrt(3)*r/2, -r/2) for the bottom left corner</li><li>(-sqrt(3)*r/2, r/2) for the top left corner</li></ul><p>We can now create a polygon with these coordinates. However, we still need to factor in offsets for the hexagon. This can be easily done by adding an offset_x value to all the x coordinates, and an offset_y value to all the y coordinates.</p><pre># points starts at top and continue clockwise<br>points = [<br>    0 + off_x, r + off_y,                       # top<br>    sqrt(3)*r/2 + off_x, r/2 + off_y,           # top right<br>    sqrt(3)*r/2 + off_x, (-1)*r/2 + off_y,      # bottom right<br>    0 + off_x, (-1)*r + off_y,                  # bottom<br>    (-1)*sqrt(3)*r/2 + off_x, (-1)*r/2 + off_y, # bottom left<br>    (-1)*sqrt(3)*r/2 + off_x, r/2 + off_y       # top left<br>]</pre><p>We can now define a function to draw a hexagon with the given parameters radius, offset_x, and offset_y. We define a dictionary mapping tile types to colours to fill in each hexagon according to what kind of tile it is.</p><pre># function to draw hexagon with given radius, and (x, y) offset<br>def draw_hex(r, off_x, off_y):<br>    colours = {<br>        &#39;desert&#39;: &#39;#ffea00&#39;,<br>        &#39;wheat&#39;: &#39;#fc9642&#39;,<br>        &#39;sheep&#39;: &#39;#c1fc42&#39;,<br>        &#39;wood&#39;: &#39;#55fc42&#39;,<br>        &#39;brick&#39;: &#39;#fc4258&#39;,<br>        &#39;ore&#39;: &#39;#7a7a7a&#39;<br>    }<br><br>    # points starts at top and continue clockwise<br>    points = [<br>        0 + off_x, r + off_y,                       # top<br>        sqrt(3)*r/2 + off_x, r/2 + off_y,           # top right<br>        sqrt(3)*r/2 + off_x, (-1)*r/2 + off_y,      # bottom right<br>        0 + off_x, (-1)*r + off_y,                  # bottom<br>        (-1)*sqrt(3)*r/2 + off_x, (-1)*r/2 + off_y, # bottom left<br>        (-1)*sqrt(3)*r/2 + off_x, r/2 + off_y       # top left<br>    ]<br><br>    canvas.create_polygon(points, outline=&quot;black&quot;, <br>                          fill = colours[tile.type], width=2)</pre><p>To actually draw the hexagons, we define a suitable radius, some base values for the x offsets, and some base values for the y offsets, and loop through every row in the board.</p><p>The y offsets linearly increase, since each hexagon decreases in height linearly (the y coordinates in a canvas start increase from top to bottom — this also means that the function draws hexagons from bottom to top, but this does not matter for our intentions). Since y offsets increase linearly, we can start the variable at some value, and increase it at each iteration. After some experimentation, the following base values were determined to be the best:</p><pre>base_y = 2.3*r<br><br>for i, row in enumerate(board):<br>    base_y = base_y + 1.7*r</pre><p>The base values for x offsets are slightly more work to figure out. Each row in our board has a different number of tiles, which increase and then decrease. We can solve this issue by defining a list called “base_xs” to store base values for the x offset, and change them at each iteration. The middle row should be drawn the most to the left, the second and fourth rows should be slightly to the right of that, and the first and fifth rows should start slightly to the right of those.</p><p>Hence, we can define the list to be the following:</p><pre>base_xs = [6*r, 5*r, 4*r, 5*r, 6*r]</pre><p>As you can see, the rows start in a staggered manner so that the board is drawn correctly (unlike the y axis, the x axis increases from left to right in a canvas). At the nth iteration, we take the base_x value to be the nth item of the list.</p><p>Within each iteration, we will need to iterate through another loop to draw each hexagon. In this loop, we add a value to the base_x value so that each hexagon is drawn to the right of the previous one. The amount we increase the base_x value by is r * 2.</p><p>To make all this clear, here is the code we write to implement all of this. This will correctly implement all the calculation we have gone through.</p><pre>base_xs = [6*r, 5*r, 4*r, 5*r, 6*r]<br>base_y = 2.3*r # 4*r - 1.7*r<br><br>for i, row in enumerate(board):<br>    base_x = base_xs[i]<br>    base_y = base_y + 1.7*r<br><br>    for i, tile in enumerate(row):<br>        # offset<br>        off_x = base_x + i * r * 2<br>        off_y = base_y<br><br>        draw_hex(r, off_x, off_y)</pre><p>We also use the “create_text” function from tkinter to write the type of tile and the token of the tile inside the hexagon:</p><pre>canvas.create_text(off_x, off_y, <br>                   text=f&quot;{tile.type} - {tile.token}&quot;, fill=&quot;black&quot;)</pre><p>When this is all combined, we get a board that looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*gMCZr_8kCrlPkBudJKkk_w.png" /></figure><p>Not exactly the best graphics, but this will do for our purposes.</p><p>We put all this into a single function called “display_results”. We will use this function to display the results we get from simulating the games, which we are finally ready to do.</p><h3>Simulation</h3><p>In order to properly count the number of times a resource is generated, we define a dictionary mapping each tile type to a number, which we will set to 0 initially. When we roll the dice, we check which resource we rolled, and increment the corresponding value in the dictionary by 1.</p><p>We can also keep track of all the rolls we got in a similar method, by making a dictionary with the numbers from 2 to 12 instead of tile types.</p><p>We then loop a certain number of times, as much as we want to in order to collect enough data. We “roll the dice” by generating two random numbers from 1 to 6, and adding them together. We then increment the correct value in both dictionaries, and repeat the loop.</p><p>The following is the function we define:</p><pre>def simulate(board, reps):<br>    count = {<br>        &#39;desert&#39;: 0,<br>        &#39;wheat&#39;: 0,<br>        &#39;sheep&#39;: 0,<br>        &#39;wood&#39;: 0,<br>        &#39;brick&#39;: 0,<br>        &#39;ore&#39;: 0<br>    }<br><br>    #  to count frequency of rolls<br>    roll_freq = {<br>        2: 0,<br>        3: 0,<br>        4: 0,<br>        5: 0,<br>        6: 0,<br>        7: 0,<br>        8: 0,<br>        9: 0,<br>        10: 0,<br>        11: 0,<br>        12: 0<br>    }<br><br>    for _ in range(reps):<br>        # generate roll<br>        roll = random.randint(1, 6) + random.randint(1, 6)<br><br>        roll_freq[roll] += 1<br><br>        # check which resources were generated<br>        for row in board:<br>            for tile in row:<br>                if tile.token == roll:<br>                    count[tile.type] += 1<br><br><br>    return count, roll_freq</pre><p>To visualise these results, we use the matplotlib library to plot the results. We first sort the results of tile types so that the frequency of resources increases from left to right on the plot.</p><p>We plot the results in the following way:</p><pre>count = {k: v for k, v in sorted(count.items(), key=lambda item: item[1])}<br><br># tile types plot<br>plt.figure(1)<br>plt.bar([k for k in count], [count[k] for k in count])<br>plt.ylabel(&quot;Number of times resources was generated&quot;)<br>plt.xlabel(&quot;Resource name&quot;)<br>plt.title(&quot;Count of resources generated over multiple rolls&quot;)<br><br># rolls plot<br>plt.figure(2)<br>plt.bar([k for k in rolls], [rolls[k] for k in rolls])<br>plt.ylabel(&quot;Number of times a number was rolled&quot;)<br>plt.xlabel(&quot;Number rolled&quot;)<br>plt.title(&quot;Frequency of rolls&quot;)<br><br>plt.show()</pre><p>This code is added into the “display_results” function.</p><h3>Visualising results</h3><p>By looping the simulate function 1,000,000 we get the following results. The particular board generated when I ran the program was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*p3Ji8PFcPEFDpu9sJxgypQ.png" /></figure><p>As expected, the distribution of rolls is completely symmetric (with there of course being some variance):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*jJY5JH9fijtwtxo4S0hoqA.png" /></figure><p>To be precise, the following list shows how many times each number was rolled:</p><ul><li>2 was rolled 28,139 times</li><li>3 was rolled 55,542 times</li><li>4 was rolled 83,190 times</li><li>5 was rolled 111,277 times</li><li>6 was rolled 138,504 times</li><li>7 was rolled 166,352 times</li><li>8 was rolled 139,129 times</li><li>9 was rolled 110,910 times</li><li>10 was rolled 83,274 times</li><li>11 was rolled 55,817 times</li><li>12 was rolled 27,866 times</li></ul><p>And finally, the graph for the frequency of resources generated was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*cYLOvBKR5z17xyQE0vqvsQ.png" /></figure><p>The specific totals are:</p><ul><li>Desert was generated 166,352 times</li><li>Brick was generated 277,741 times</li><li>Wheat was generated 306,275 times</li><li>Ore was generated 333,055 times</li><li>Wood was generated 333,447 times</li><li>Sheep was generated 360,773 times</li></ul><h3>Analysing the results</h3><p>As expected, the distribution of rolls is completely symmetric with a little variation. 7 was of course rolled the most, since it has the highest probability of being rolled with 2 dice.</p><p>Much more interesting is the distribution of frequencies of resources generated. While 7 is the most likely number to be rolled, it still has a lower probability than all other numbers combined. Hence, it makes sense that the desert tile was rolled the least.</p><p>By examining the board that was generated, we can see that sheep tiles have the highest probabilities of being landed on, with tokens 3, 6, 9, and 11. Sheep tiles have a probability of 13/36 = 36% to be generated. This figure is found by adding the probabilities of rolling a 3, a 6, a 9, and an 11 by rolling 2 dice.</p><p>In fact, here are the probabilities of all the different types of tiles being generated:</p><ul><li>Sheep: 13/36 = 36%</li><li>Wood: 12/36 = 33%</li><li>Ore: 12/36 = 33%</li><li>Wheat: 11/36 = 31%</li><li>Brick: 10/36 = 28%</li><li>Desert: 6/36 = 17%</li></ul><p>We can see that these match very well with the distributions we got from the simulation. Wood and Ore were generated approximately the same number of times, only differing by around 400, or around 0.04%. Sheep is generated the most, and desert generated the least.</p><h3>Evaluation of this method</h3><p>These results can help to see that, as expected, the tiles with tokens that are more likely to be rolled, are generated more. This is a very obvious result, and is what you get when repeatedly rolling dice, especially if you roll the dice 1,000,000 times.</p><p>However, this does not give a realistic picture of a generic Catan game. On average, each game only lasts for around 80 rolls of the dice. Repeating this process a million times won’t give an appropriate representation for a game. If we run the simulate function 80 times, with the following board, we get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*cuoKwjKqQ1l8CkHbWZiMvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*LXMQ7Trlggc2fNP4Go1QPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*wLHGqHAv0KppGkui8zb2sQ.png" /></figure><p>As you can see, with the wheat resource being stacked so heavily with two 6 tokens, wheat is the resource that is generated the most. Desert is again generated the least, since it has the same probability of being generated for each game.</p><p>The distribution of rolls is much more skewed and not symmetric with only 80 rolls. The highest is still 7, which was rolled 14 times.</p><p>Repeating the simulation only 80 times provides more helpful results, whereas repeating the simulation a large number of times provides expected results.</p><p>If we repeat the simulation 80 times, keep track of all the frequencies of tile types and rolls, and repeat that process multiple times, we could get an estimate for the average number of times a particular resource is generated, and a particular number is rolled.</p><h3>Repeating multiple games</h3><p>To keep track of all the data, we again create two lists — one to keep track of resources generated, and one to keep track of numbers rolled. We will store the dictionaries that are generated by the simulate function in these lists.</p><p>We then simply enter a loop. At each iteration, we create a new board, run the simulate function 80 times, and add the dictionaries generated to their respective lists. The following is the function we define:</p><pre>def game_sim():<br>    counts, rolls = [], []<br>    reps = 1_000_000<br><br>    for _ in range(reps):<br>        board = gen_board()<br>        count, roll_freq = simulate(board, reps=80)<br>        counts.append(count)<br>        rolls.append(roll_freq)<br><br>    return counts, rolls</pre><p>To now plot this data, we need to extract and handle it. We can define a generic function that takes in a list of dictionaries, and plots them. Inside the function, we need to first take our list of dictionaries, and format it so that we can easily plot the data. If we have a list dictionaries mapping resources to the number of times they were generated, we can first turn it into a dictionary mapping the resource to a list containing the number of times the resource was generated.</p><p>For example, if the data that we pass in looks like:</p><pre>[<br>{&#39;desert&#39;: 16, &#39;wheat&#39;: 38, &#39;sheep&#39;: 31, &#39;wood&#39;: 22, &#39;brick&#39;: 12, &#39;ore&#39;: 18},<br>{&#39;desert&#39;: 18, &#39;wheat&#39;: 25, &#39;sheep&#39;: 22, &#39;wood&#39;: 29, &#39;brick&#39;: 18, &#39;ore&#39;: 29},<br>{&#39;desert&#39;: 21, &#39;wheat&#39;: 22, &#39;sheep&#39;: 22, &#39;wood&#39;: 33, &#39;brick&#39;: 15, &#39;ore&#39;: 21},<br>...<br>]</pre><p>We want to turn this into something that looks like:</p><pre>{<br>&#39;desert&#39;: [16, 18, 21, ...],<br>&#39;wheat&#39;: [38, 25, 22, ...],<br>&#39;sheep&#39;: [31, 22, 22, ...],<br>&#39;wood&#39;: [22, 29, 33, ...],<br>&#39;brick&#39;: [12, 18, 15, ...],<br>&#39;ore&#39;: [18, 29, 21, ...]<br>}</pre><p>Which we can then use to find average values of the lists, to then graph.</p><p>To collect all the data into one list for each key in the dictionary, we first make an empty dictionary called “all_vals”. We then go through all the elements in the first dictionary in our main list, and map each key to an empty list in all_vals.</p><p>We then iterate through all elements in our main list and simply add the value to the list of each respective resource in the all_vals list.</p><pre># create dict mapping keys to list of all rolled values<br>all_vals = {}<br><br>for k in data[0]:<br>    all_vals[k] = []<br><br>for elt in data:<br>    for k in elt:<br>        all_vals[k].append(elt[k])</pre><p>Finding the average of each list is pretty easy, we loop through each key, and just take the sum of the list and divide it by the length of the list. We store this in a dictionary called “avg_vals”.</p><pre># create dict mapping keys to average values<br>avg_vals = {}<br><br>for elt in all_vals:<br>    avg_vals[elt] = sum(all_vals[elt]) / len(all_vals[elt])</pre><p>We can then use matplotlib once again to plot the data.</p><pre># plot dict of average values<br>plt.figure(fig_num*10+fig_num)<br>plt.bar([k for k in avg_vals], [avg_vals[k] for k in avg_vals])<br>plt.ylabel(&quot;Average number of times X was generated&quot;)<br>plt.xlabel(&quot;X&quot;)<br>plt.title(&quot;Average frequency of generating X&quot;)</pre><p>Here are the results we get when we plot our data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*XwDgq5K1wIEXSXU0rFcFcQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*7vhl7n8TMHHz5nG-U71kCw.png" /></figure><p>The distribution of numbers rolled is exactly as expected — perfectly symmetrical. The distribution of resource generation is much more interesting. Wheat, Sheep, and Wood are generated much more commonly than Brick and Ore, and all other resources are generated more than the desert. In this particular run of the program,</p><ul><li>Desert was generated 13.3405 times on average</li><li>Wheat was generated 28.6446 times on average</li><li>Sheep was generated 28.6244 times on average</li><li>Wood was generated 28.6343 times on average</li><li>Brick was generated 21.4826 times on average</li><li>Ore was generated 21.4889 times on average</li></ul><p>You can see that the average number of times that Wheat, Sheep, and Wood were generated differs only by a little. As does the average number of times Brick and Ore was generated. These figures make sense if you look at the number of tiles each resource has — there are 4 Wheat, Sheep, and Wood tiles, while there are only 3 Brick and Ore tiles. It makes sense that we get the distribution that we get by looking at this.</p><h3>Conclusion</h3><p>To conclude, the Wheat, Sheep, and Wood resources should be generated the most in every game on average. This makes sense since there are more tiles of those resources in the game.</p><p>In a single game, the tiles that have tokens with high probabilities are generated more, which also makes sense — just purely due to the laws of probability.</p><p>The distribution of rolls across several games and also a single game is perfectly symmetrical, as expected.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8d91b518e71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advantage in Dungeons and Dragons]]></title>
            <link>https://medium.com/@varadkulk123/advantage-in-dungeons-and-dragons-ce6c60bfebf3?source=rss-4e436bf8080c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce6c60bfebf3</guid>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[luck]]></category>
            <category><![CDATA[dnd-5e]]></category>
            <category><![CDATA[dice]]></category>
            <category><![CDATA[dnd]]></category>
            <dc:creator><![CDATA[Varad Kulkarni]]></dc:creator>
            <pubDate>Sun, 26 Feb 2023 16:58:04 GMT</pubDate>
            <atom:updated>2023-02-26T16:58:04.858Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dlLaoW4KnEJJkCiG" /><figcaption>Photo by <a href="https://unsplash.com/@clintbustrillos?utm_source=medium&amp;utm_medium=referral">Clint Bustrillos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In Dungeons and Dragons, when you make a roll with a d20, there are various ways to gain “advantage” or “disadvantage” on that roll. What this means is that you roll 2 dice, and then choose the highest value if you have advantage, or choose the lowest if you have disadvantage.</p><p>This can be used in many situations, like rolling to attack, making a save, an ability check, etc. It can also be given by different sources, like the DM granting it to the player, or the character using some of their features and traits. For example, if the player is playing a Barbarian, they can make their character Rage, which grants advantage on all of their Strength based ability checks and saving throws. Spells can also grant this effect, by making target easier or harder to hit by imposing advantage or disadvantage.</p><p>This of course changes the probabilities of rolls, and how difficult or easy it is to succeed a throw.</p><h3>Advantage</h3><p>To reiterate, when you roll with advantage, you roll two dice and take the higher outcome. Using this we can construct a table of rolls.</p><p>The horizontal and vertical axes will be the numbers rolls on each dice, and the box corresponding to each row and column will be the result of rolling with advantage. This is assuming the player is rolling a d20. The following is the table that is made:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*yAIEsA9bdng4X1jBTnjWfw.png" /></figure><p>You can see clear patterns here, if we take the highest of two rolls. Here are some probabilities:</p><p>The probability of getting a 1 (rolling 2 natural 1s) is 1 in 400 (0.25%). You can see that getting advantage really reduces the chances of getting a 1. Compared to the 5% chance of getting a natural 1 without advantage, you can see that the chances of getting a natural 1 are 20 times less than normal.</p><p>The probability of getting a natural 20 is (20 + 19) in 400 → 39 in 400 (9.75%). This is compared to the normal chance of getting a natural 20, which is only 5%. It makes sense that rolling 2 dice would almost double the chances of a natural 20.</p><p>For each number, the number of ways to get said number increases by 2. For example, the number of ways of getting a 4 is 7, and the number of ways of getting a 5 is 9. You can also quickly get the number of permutations for getting a roll n by doing n + (n-1) = 2n-1.</p><h3>Disadvantage</h3><p>We can make a similar table for disadvantages. This is done by rolling two dice and taking the lower number. Here is the resulting table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*fZzu910NNIgmnu5KQczWrA.png" /></figure><p>You can see that the results are sort of “flipped”, with getting a natural 20 being only a 1 in 400 chance, and getting a natural 1 being a 39 in 400 chance. Each probability is swapped with it’s “mirror” number — 1 is swapped with 20, 2 with 19, 3 with 18 and so on.</p><p>Here, you can get the permutations for getting a roll n by doing <br>(21-n) + (20-n) = 41–2n.</p><p>We subtract n from 21 so that 20 is set to 1, 19 is set to 2, and so on — each value is once again “mirrored”. Since it is mirrored twice, we can use a variation of the formula for advantage.</p><h3>Probabilities</h3><p>Here you can see the probabilities obtained when rolling with advantage and disadvantage. The data on the left shows the probabilities for advantage rolls, and the table on the right shows probabilities for disadvantage rolls:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*DDVmFoK12P1seqSSJfgC2A.png" /></figure><p>You can see that one is the inverse of the other.</p><h3>A third dice</h3><p>Usually in Dungeons and Dragons, advantage or disadvantage cannot be imposed more than once. If it is, through some combination of feats, features, traits, or the DM, it is simply cancelled down into a single extra die.</p><p>But what if you <em>could</em> have triple advantage/disadvantage? We could make a 3D cube of results of rolls to illustrate this but that is hard to generate, so we can instead use maths.</p><p>If we look at the top left corner of our advantage table, we can see that the 2s almost make a square, if it were not for the 1. The 3s also almost make a square, if it were not for the 2s and 1. This can show us that we can get the number of permutations using square numbers.</p><p>We can generate the permutations for n by doing the following:</p><p>We take n², and then subtract (n-1)² from it. Let me explain.</p><p>Suppose we want to find the probability for getting a 6. We can take 6² “cells”, and subtract 5² cells from there, to leave us with our previously calculated 2n-1 formula. You can see it illustrated here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*UEqgCtjZQ_6-0_sHCSFGyg.png" /></figure><p>Here we are left with the grey cells, giving us $6+5 = 11$ ways to roll a 6, which matches our calculated value above.</p><p>In fact, our new formula evaluates to the same formula we calculated previously:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*5SWT1LpKcLllv1wTzaK4lg.png" /></figure><p>We can then apply this to our cube of rolls. A cube of rolls for advantage would have a single 1 in the top, in the case that 1s are rolls 3 times (a probability of 1 in 8000 — 0.0125%). We then have almost a cube of 2s surrounding the 1. There would be a 2 by 2 by 2 cube of 2s, with one cube being a 1. We can see that there would be 7 cubes of 2s, giving a probability of 7 in 8000 — 0.0875%. We can continue this pattern, and generalise it like we did with the table of rolls.</p><p>For finding the probability of getting n in 3 rolls with advantage, we take n³ and subtract (n-1)³:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*Jb7HLAtqZ8pO4ZIOK8LS9w.png" /></figure><p>For n = 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*mHwLzmm_RraCsQaEkx__VA.png" /></figure><p>For n = 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*m2-M9jnTqRFJCo-I3uDxeg.png" /></figure><p>As you can see, this follows our predictions perfectly. We can also construct a table for these probabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*YBDor3T1c-Hou0aWoFDR6A.png" /></figure><p>Now for disadvantage with a third dice.</p><p>Let’s start with generalising the 2D table like before. Since the squares are now on the bottom right instead of the top left, we can take a similar approach.</p><p>To find the probability of getting n with 3 dice, and disadvantage, we subtract n from 21 and apply the same formula. Let m = 21-n. The formula is then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*oEPd3UlV4uJbzVa8HT_a9A.png" /></figure><p>Substituting 21-n back into m:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*KgVQFc6856wiExd35OJccw.png" /></figure><p>This matches our previous formula.</p><p>We can apply the same logic to our cube with 3 dice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*ruP2_WlX1s54ecFqFYzuLg.png" /></figure><p>We can once again create a table with this formula, and compare it with the table for advantage. Once again, the probabilities for advantage is on the left, and the table for disadvantage is on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*_XpYMDKJd4A8j9oe1glIaA.png" /></figure><p>You can again see that the two sides are the inverse of each other, the probability for 20 on one side and the probability for 1 on the other are the same, and so on for all other numbers in the table.</p><h3>Lucky feat</h3><p>There is a feat in DnD called Lucky. This allows you to roll an extra dice for any roll by spending a luck point, and choose which dice to use. This can also stack on top of advantage/disadvantage. This means that, in specific circumstances, the player can actually gain advantage on 3 dice, effectively gaining super advantage. Even if you have disadvantage, you can roll an extra dice, and choose the outcome, turning disadvantage into a very advantageous roll.</p><p>Using this, more than doubles the chances of rolling a natural 20 from 5% to 11.41%, and reduces the chance of a natural one from 5% to a mere 0.01%.</p><h3>Conclusion</h3><p>By adding a bit of maths and probability, we can see how effective advantage and disadvantage is in skewing the chances of the player, either for or against them. We worked out formulae to find the number of ways of rolling a certain number. In fact, we can generalise the formulae even further, to get the following:</p><p>For advantage, with n being the target roll, and m being the number of dice, the probability of rolling n is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*6x8RPnnVp5j3l0OycBhTEQ.png" /></figure><p>In fact, the chances of rolling a 20 as the number of dice increases, is 1, since the player only needs to roll 20 once in order for that to be the result of the rolls.</p><p>With disadvantage, the probability is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*-nh7zMsvu3OAXiAFTtAlrg.png" /></figure><p>Predictably, the chances of getting a 20 as the number of dice increases, is 0.</p><p>Intuitively, the probabilities of rolling n or higher (i.e. beating a DC) with advantage is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/1*2tKSgO_vvnCnO08TWGYyvg.png" /></figure><p>And with disadvantage, it is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/108/1*2iNzw9xb5MvjBU-qkiu2JQ.png" /></figure><p>In conclusion, adding advantage and disadvantage can greatly affect the outcome of the event. Considering this, and the fact that there are no prerequisites to taking the feat, Lucky is a very good feat to take, and could be a game changing feat in some situations. Even just adding advantage to 3 rolls per long rest seems incredibly useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce6c60bfebf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Truth tables and logic gates]]></title>
            <link>https://medium.com/@varadkulk123/truth-tables-and-logic-gates-2ab4566cfc1c?source=rss-4e436bf8080c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ab4566cfc1c</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[binary]]></category>
            <category><![CDATA[logic]]></category>
            <category><![CDATA[logic-gates]]></category>
            <dc:creator><![CDATA[Varad Kulkarni]]></dc:creator>
            <pubDate>Sat, 25 Feb 2023 19:15:27 GMT</pubDate>
            <atom:updated>2023-02-25T19:15:27.359Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jfNAoYsWr7ZMmsi3" /><figcaption>Photo by <a href="https://unsplash.com/@swimstaralex?utm_source=medium&amp;utm_medium=referral">Alexander Sinn</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>We use some form of computers every day, be it a phone, a laptop or even a calculator. But how do these machines work, how do they know what humans want them to do, while only understanding the binary language of 1s and 0s, which is essentially just on or off?</p><p>This is an essay which attempts to explore the very starting point of how computers can think, how they can perform calculations much much quicker than any human, with only 1s and 0s.</p><h3>Logic Gates</h3><p>To understand computers and their logic, you need to first understand the different types of logic, otherwise called logic gates. These are devices that take in some binary inputs, and help build circuits. These inputs are usually in the form of 0s and 1s, 0 signifying false, and 1 signifying true. Logic gates perform basic logical functions that are fundamental to digital circuits. Most logic gates have 2 inputs, and 1 output. The output is also binary, like the inputs.</p><h3>Truth tables</h3><p>Truth tables are tables that show the inputs and outputs of a logic gate or circuit, for every possible input.</p><p>For an AND gate, the truth table may look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*e_IBaQjtejcWYE8fuVomTg.png" /></figure><p>As you can see, the output is only true if both input A AND input B are true. You can also see that every possible iteration of the inputs is covered for.</p><h3>Basic logic gates</h3><p>There are seven basic logic gates:</p><ol><li>AND</li><li>OR</li><li>XOR</li><li>NOT</li><li>NAND</li><li>NOT</li><li>XNOR</li></ol><p>Here are the basic explanations for them, and their truth tables:</p><p><strong>AND gate</strong></p><p>As seen above, the AND gate output is only true if both inputs are true. Here is the truth table again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*ZmFFSuWMD2tmsah2SdqJDA.png" /></figure><p><strong>OR gate</strong></p><p>The OR gate works how you might expect, the output is true if input A OR input B is true. Here is the truth table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*6XHEEN7niZPjfc1HOpopcg.png" /></figure><p><strong>XOR gate</strong></p><p>This gate is slightly harder to understand than the previous ones. XOR stands for exclusive-OR, and can be thought of as “either”. The output for this gate is true if either input A or input B is true, but not both of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*kulz_vovIEzA6a8e_qYyRw.png" /></figure><p><strong>NOT gate</strong></p><p>A not gate simply flips the input. This gate only has 1 input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*TaaDd4CM_nXJ3Gu6RBh33A.png" /></figure><p><strong>NAND gate</strong></p><p>This gate is simple, since it is the combination of two gates. This gate combines the AND gate and the NOT gate, negating the outputs of an AND gate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*aB2ntjtBSfDtmuL0_5cX0w.png" /></figure><p>Note that all of the inputs are flipped compared to an AND gate. The output is only true if at least one of the inputs is false, otherwise (if both inputs are true) the output is false.</p><p><strong>NOR gate</strong></p><p>This gate is also simple, since it is the combination of the OR gate and the NOT gate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*F4MCa-0ajKFRdRSTAU3agw.png" /></figure><p>The output to this gate is only true if both inputs are false, otherwise it is false.</p><p><strong>XNOR gate</strong></p><p>This is the combination of the XOR and the NOT gates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*Jb5bzA1f1ouv9WCW-m3oAQ.png" /></figure><p>Note that the output is only true if both inputs are the same, i.e. both false or both true, and is false otherwise.</p><p>A fun fact about logic gates, every single gate here can be built with a combination of AND and NOT gates.</p><h3>Programming gates into functions</h3><p>Before moving on to the next section, let’s program these into functions we can use, in python.</p><p>For the AND and OR gate, python already has keywords that perform this operation for us:</p><pre>def AND(a, b):<br>  return (a and b)</pre><pre>def OR(a, b):<br>  return (a or b)</pre><p>As you can see, in both functions, we can user python’s “and” and “or” keywords to take in two inputs, a and b, and return the appropriate output.</p><p>Since the XNOR gate is the XOR gate but inverted, it follows that the XOR gate is the XNOR gate but inverted. Since the XNOR gate just checks if the two inputs are equal, we can negate that for the XOR function, and check if the two inputs are different.</p><pre>def XOR(a, b):<br>  return (a != b)</pre><p>The NOT gate is simple, we just return the negation of the input.</p><pre>def NOT(a):<br>  return (not a)</pre><p>The NAND and NOR gates are also simple since we can take the previously defined functions, and negate their outputs.</p><pre>def NAND(a, b):<br>  return NOT(AND(a, b))</pre><pre>def NOR(a, b):<br>  return NOT(OR(a, b))</pre><p>And finally, the XNOR gate just checks if the two inputs are the same.</p><pre>def XNOR(a,b):<br>  return (a == b)</pre><p>If we run a little test function to make a sort of truth table for us, we get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*KSdrhnw1dzmw7oyj2fRSag.png" /></figure><p>As you can see, this almost matches perfectly with the truth tables we had earlier, we just need to make sure the last 4 logic gates convert their output into binary, instead of a boolean expression. We can do this easily with a built in function in python — int(). This can convert a boolean expression into either a 1 or a 0, depending on the expression.</p><p>And by simply adding an int() in each function where it was required, we have the perfect outputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*86dOZ4PC78xthkISGuxQaw.png" /></figure><h3>Building an adder</h3><p>We now want to make some sort of combination of these logic gates that allows us to add 2 4-bit numbers. In theory, this combination, or algorithm, should be able to take something like 7 + 4, and output 11. Since we want to add 4-bit numbers (numbers that can be represented by 4 bits or less), the input will a total of 8 bits.</p><p>Let’s first program a function to convert decimal numbers into binary, and vice versa. Luckily, python has some built in functions that allow us to do this easily.</p><pre>def decToBin(n):<br>  return int(bin(n).replace(&quot;0b&quot;, &quot;&quot;))</pre><pre>def binToDec(n):<br>  return int(str(n), 2)</pre><p>In the first function, the bin() function takes in an integer, and converts it into binary. It returns the answer with a “0b” in front, so we can just get rid of that. It also returns the value as a string, so we need to convert it into an integer.</p><p>For the second function, we can again use the int() function, to convert the decimal number into base 2 — binary.</p><p>Now that we can easily convert between bases, let’s see what we actually need to make. We’ll start with adding 2 1-bit numbers (either 0 or 1) to simplify the problem.</p><p>Since we are adding 2 1-bit integers, we need to output fields, one is the Sum — the actual addition of our 2 bits, and the other is the Carry. The Carry field is similar to the number you “carry over” when doing chimney sums. Ideally, this would be the expected output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*hDbhHsHhp67_q2PnECerAg.png" /></figure><p>If we look at our sum and carry fields, we can see that the truth table matches one of the logic gates we already have. The Carry output is the same as the output of the AND gate, and the Sum output is the same as the output of the XOR gate.</p><p>This means we can hook up our inputs into these two gates, and get the exact output we want. The following is a flowchart of what we want to happen. The two inputs are given to both the AND and the XOR gate, and outputted as the Sum and the Carry:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*t_2zfVwJQLJvU0R2aQhXdQ.png" /></figure><p>We can of course program a function for this:</p><pre>def adder(a,b):<br>  return int(AND(a,b)), int(XOR(a,b)) # carry, sum</pre><p>And testing it, we get this output, which is exactly what we want:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*v8jHvtDm-8JmlxEjAuKBIw.png" /></figure><p>Now, what if we want to chain a bunch of these together, in something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/73/1*2Fp9P3r4NAjs22RMQw1V-A.png" /></figure><p>As a normal chimney sum, we start from the right. We can of course feed in the two 1s into our adder function, and we get a 1 in the Carry output, and a 0 in the sum output. So, as a chimney sum, we place the carry in the next column, and write down the sum under the current column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/67/1*U9tGSkW4bNsScKyeAXg2lg.png" /></figure><p>Now proceeding onto the second column, we have a problem. We need to add 3 bits, 1, 0, and 1, but we only have two inputs in our adder function. We can solve this by adding a third input called Carry In. We will once again make a truth table of what the Sum and Carry outputs should be when we have a Carry In, although what we are essentially doing is adding 3 1-bit numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*27qOjG33A-2TGmc8R_ds-Q.png" /></figure><p>Now, these truth tables won’t match any of the logic gates we already have, since we have three inputs, so we will have to combine a few logic gates.</p><p>Let’s start with adding the output of Input A + Input B onto Carry In. We can get Input A + Input B as we did earlier by inputting them into an XOR gate. We can then use another XOR gate to add the output with Carry In:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*l_RO5UCymh1FhqQhjeiU0w.png" /></figure><p>We once again may need to carry over a bit, so we can add an AND gate, as before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZI3JxGnIF_LaRh-1j_VDg.png" /></figure><p>Now, if either one of the Carry outputs (either Carry of A+B or Carry of (A+B) + Carry In) is 1, we need to carry it over. We can simply use an OR gate for this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*uETqCn39PldCrMEgKbA3sg.png" /></figure><p>And, since the middle XOR gate is the sum of all 3 inputs, we can just output that as the total Sum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*4k98_M0ODmhrssFJpFAEbw.png" /></figure><p>This is a complete adder, taking in 2 inputs, and a Carry In, and outputting the Carry bit and Sum bit of the 3 inputs added together. Let’s make this into a function so we can use it later:</p><pre>def adder(a,b,c):<br>  carry = OR(AND(a,b),AND(XOR(a,b),c))<br>  _sum = XOR(XOR(a,b),c)<br>  return _sum, carry</pre><p>Testing every output returns the exact same result as our truth table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*ISIi-Tntab9Joy2TTSa7iA.png" /></figure><p>The function may seem convoluted, but it is the exact same as the flowchart, just very compact.</p><h3>Final steps</h3><p>Now onto finally creating the 4 bit adder. To reiterate, we want to take in 2 numbers that can be represented in 4 bits or less, convert them into binary, add them together, output a binary number of 4 bits, and convert it to decimal. Making a truth table for this would take a long time, and the table itself would be very large, so instead, let’s work through the logic.</p><p>The first step — converting the 2 numbers into binary — is simple, we use our premade functions:</p><pre>def fourBitAdder(num1, num2):<br>  bin1 = decToBin(num1)<br>  bin2 = decToBin(num2)</pre><p>If we have a number that is able to be represented in less than 4 bits, the function will use as little bits as possible. For example, the number 6 would be converted into 110, and not 0110. We want all numbers to be 4 bits long, so we will need to pad the bin1 and bin2 variables with extra 0s if necessary:</p><pre>def fourBitAdder(num1, num2):<br>  bin1 = str(decToBin(num1)).zfill(4)<br>  bin2 = str(decToBin(num2)).zfill(4)</pre><p>We will also need to get the individual bits from the binary numbers, and we will store them in a list:</p><pre>def fourBitAdder(num1, num2):<br>  bin1 = str(decToBin(num1)).zfill(4)<br>  bin2 = str(decToBin(num2)).zfill(4)<br><br>  bin1Bits, bin2Bits = [], []<br><br>  for bit in bin1:<br>      bin1Bits.append(int(bit))<br><br>  for bit in bin2:<br>      bin2Bits.append(int(bit))</pre><p>Now that we have our data ready to use, let’s make a flowchart just so we are clear on what we are doing. To make things easier, here is a guide on the inputs and outputs of the Adder function. For convenience, we’ll output the Sum on top, and the Carry on the bottom:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*IoBAPzGXSL_B3Zj0WRzBNQ.png" /></figure><p>On the left is what will be inputted in, and the right is what the output will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8wjNBr7Ub9wE8NsTwBcdyQ.png" /></figure><p>Note that we have a Carry In, which we will need to add into the program:</p><pre>def fourBitAdder(num1, num2, carryIn):<br>  bin1 = str(decToBin(num1)).zfill(4)<br>  bin2 = str(decToBin(num2)).zfill(4)<br><br>  bin1Bits, bin2Bits = [], []<br>  for bit in bin1:<br>      bin1Bits.append(int(bit))<br><br>  for bit in bin2:<br>      bin2Bits.append(int(bit))</pre><p>To put into context, if we wanted to add 6 and 7, this is what we want to happen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*534liCMf7ZjdBi5VZ8kbLg.png" /></figure><p>Note that the bit in the place of Bit 4 is the last bit — reading the binary numbers goes from top to bottom.</p><p>To try and work out what needs to take place between the input and output, let’s go back to our chimney sum. Here is the same problem in a chimney sum, with the top row representing the carry, the second row representing the number 6, and the third row representing the number 7:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*aGRROj2HcdHDQHOjaPW3LA.png" /></figure><p>The way we carry out a chimney sum is by starting from the right. We first add the last two bits of 6 and 7, and of course the carry, if we have one. Since this is the first addition, we do not have a carry bit. The last two bits added together is 1, and we write that down at the bottom. Then onto the next row, where we carry out the same procedure, and so on until we complete the last row. If the last row had a total which required a carry, that would go into the carry bit.</p><p>We can replicate this process using our Adder function we made earlier. First, we input the carry bit, and Bit 4 of both numbers into an Adder: (to make the diagram easier to view and understand, Number 1 will have red arrows, Number 2 will have yellow arrows, and any Carry will have green arrows).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*cXtt5Au-VJTQJmVFu3pcGw.png" /></figure><p>Continuing with the chimney sum, we then add the carry of this first adder, and the Bit 3 of both numbers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*cI5rL_gOufsoe7BJ_9apiQ.png" /></figure><p>And we continue this process, until the very last bit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KlR_N322WDsphuToX2JI9w.png" /></figure><p>Now, all inputs are fed into an Adder, so we just need to output them appropriately. Starting at the first Adder, the output of the adding the 4th bit of both numbers should correspond to the 4th bit of the final Sum, so we’ll output it there. The same goes for the other adders, they would output into their respective bits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4MIMoMk6BoIf3riKcD6JQ.png" /></figure><p>Now we have one final point to connect, and that’s the Carry bit, which we can get from the carry output of the last Adder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4VwWo8N4bbMl2y_6hjJGoA.png" /></figure><p>We finally have the completed algorithm for our 4 bit adder. Now, let’s program it in.</p><p>For the algorithm, we can add in the following code to the function. Since adder returns sum then carry in a tuple, we can access it using indexing — 0 is sum and 1 is carry.</p><pre>adder1 = adder(bin1Bits[3], bin2Bits[3], carryIn)<br>adder2 = adder(bin1Bits[2], bin2Bits[2], adder1[1])<br>adder3 = adder(bin1Bits[1], bin2Bits[1], adder2[1])<br>adder4 = adder(bin1Bits[0], bin2Bits[0], adder3[1])<br><br>carry = adder4[1]<br>_sum = [adder4[0], adder3[0], adder2[0], adder1[0]]</pre><p>Now, we have the carry bit, and the sum bits, but the sum bits are in a list, so we should convert them back into decimal.</p><pre># convert list into string ([1, 1, 0, 1] -&gt; &quot;1101&quot;)<br>s = [str(integer) for integer in sum] <br>s = &quot;&quot;.join(s)<br>sum = binToDec(s)</pre><p>So, this is what the final function looks like:</p><pre>def fourBitAdder(num1, num2, carryIn):<br>  # data handling<br>  bin1 = str(decToBin(num1)).zfill(4)<br>  bin2 = str(decToBin(num2)).zfill(4)<br>  <br>  bin1Bits, bin2Bits = [], []<br>  for bit in bin1:<br>      bin1Bits.append(int(bit))<br>  <br>  for bit in bin2:<br>      bin2Bits.append(int(bit))<br>  <br>  # 4-bit adder algorithm<br>  adder1 = adder(bin1Bits[3], bin2Bits[3], carryIn)<br>  adder2 = adder(bin1Bits[2], bin2Bits[2], adder1[1])<br>  adder3 = adder(bin1Bits[1], bin2Bits[1], adder2[1])<br>  adder4 = adder(bin1Bits[0], bin2Bits[0], adder3[1])<br>  <br>  carry = adder4[1]<br>  sum = [adder4[0], adder3[0], adder2[0], adder1[0]]<br>  <br>  # convert sum from binary to dec<br>  # convert list into string - [1, 1, 0, 1] -&gt; &quot;1101&quot;<br>  s = [str(integer) for integer in sum] <br>  s = &quot;&quot;.join(s)<br>  <br>  sum = binToDec(s)<br>  <br>  print(f&quot;Process: {num1} + {num2}\nResult: Total is {sum}, carry is {bool(carry)}&quot;)</pre><p>Let’s test it out!</p><p>When we run the function with these values:</p><pre>fourBitAdder(6, 7, 0)<br>fourBitAdder(10, 2, 0)<br>fourBitAdder(8, 10, 0)<br>fourBitAdder(1, 1, 0)</pre><p>Here is the result:</p><pre>Process: 6 + 7<br>Result: Total is 13, carry is False<br>Process: 10 + 2<br>Result: Total is 12, carry is False<br>Process: 8 + 10<br>Result: Total is 2, carry is True<br>Process: 1 + 1<br>Result: Total is 2, carry is False</pre><p>As you can see, for values that are higher than 16, the carry bit is True, and the sum value is the total mod 16. For example, if we had decided to add together 15 and 9, the total would be 24, but the sum value that the 4 bit adder comes up with is 24 mod 16 = 8, and the carry bit would be True. The carry bit being True is the signal that the total is too high for the bits to represent.</p><h3>Conclusion</h3><p>After all this work, we have finally been able to add numbers under 16 together, which really puts into perspective how much work computers are doing every millisecond. We haven’t even touched on negative numbers, or doing arithmetic with negative numbers.</p><p>The only reason I am able to explain this at all is due to it being engineered and worked on and built up by hundreds and thousands of computer scientists and computer engineers in the past. Imagine we had no knowledge of computers, how would you even know where to start with making something like this? Imagine being the first to invent these methods of making a bunch of metal and silicon think and be able to do complex calculations a hundred times quicker than any person.</p><p>I love that we have the technology and capability to achieve this incredible feat of engineering today, and with quantum computing gaining popularity, who knows what could be possible with instantaneous computing speeds.</p><p>Getting down to the pure basics, the bare bones of 1s and 0s really shows how impressive and advanced even the first computers were. Being able to invent these machines is truly one of, if not the greatest feat of humanity. To put electricity into a rock and have it produce art, games, movies, and anything else you can imagine is truly wonderful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ab4566cfc1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Group theory — the monster group]]></title>
            <link>https://medium.com/@varadkulk123/group-theory-the-monster-group-9adbfad7eeac?source=rss-4e436bf8080c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9adbfad7eeac</guid>
            <category><![CDATA[symmetry]]></category>
            <category><![CDATA[group-theory]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Varad Kulkarni]]></dc:creator>
            <pubDate>Sat, 25 Feb 2023 17:23:31 GMT</pubDate>
            <atom:updated>2023-02-25T17:23:31.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-8Dom7DFhx2x_yXY" /><figcaption>Photo by <a href="https://unsplash.com/@erol?utm_source=medium&amp;utm_medium=referral">Erol Ahmed</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Group theory — the monster group</h3><h3>Introduction</h3><p>The branch of mathematics called group theory is all about symmetries, and groups of symmetries, which I will go on to explain. There is one such group labelled the Monster Group. This group is a collection of 26 other smaller groups (although these “smaller” groups are still huge), and has an “order” of around 8*10⁵³, which is absolutely huge. It is also proved to exist in a 196,883 dimensional space. I’ll get onto what all this means in a bit, but this should give you a scale of what is to come in the following essay.</p><h3>Symmetries</h3><p>When I talk about symmetries, you may think of the lessons in around the first year of high school when you learned about symmetrical shapes. You also may have learned that there are two different types of symmetries — rotational symmetry and mirror symmetry.</p><p><strong>Rotational Symmetry</strong></p><p>A shape is rotationally symmetric when you can rotate it some degrees, and it appears the same as the original shape.</p><p>For example, if we have an equilateral triangle, and rotate it anti-clockwise by 120°, we would get another equilateral triangle. This looks the same as the previous triangle, but the points of the triangle have moved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*SC4zfZF7boLmt77FXK7dXw.png" /></figure><p>A similar thing happens if we rotate it 240°. Note that this is the same as rotating 120°clockwise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*jp85gg5bfWqLRGJVRjuOiw.png" /></figure><p><strong>Mirror Symmetry</strong></p><p>A shape is also symmetric when it can be mirrored, or flipped, along some axis, and still look the same as the original shape.</p><p>If we take the example of the equilateral triangle again, we can flip the triangle along the line from point A vertically downwards, perpendicular to the line CB. I’ll call this axis “a” to make it easier to reference. With this transformation, the two points C and B are swapped, while the point A does not move position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*01aaHBg1mQnpAb0LW6pMqQ.png" /></figure><p>There are two more mirror symmetries — “b” and “c”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*i2SRMvCqN5yj0eR2JgB87Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ijv6mN91hBht9dZnC-BDXw.png" /></figure><p>In each of these symmetries, the point that is on the axis of symmetry does not move, while the other two points are swapped.</p><p><strong>Combining Symmetries</strong></p><p>Let us first put all of the symmetries that we have into a single group. We will call it G for Group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*Ac6muim8jikl_aKAOeQkKg.png" /></figure><p>The R represents the rotation symmetries, and the number is how many degrees to rotate. The letters are the mirror symmetries. Note that the “do nothing” element is in this group, R_0, and the number of elements in this group is 6 — an equilateral triangle has 6 symmetries.</p><p>Using just these 6 symmetries, we can combine two of them, to get another symmetry that is already in this group.</p><p>For example, you could combine the “a” and R_120 to get “b”. This is written as “a” * R_120 = “b”, and this is how it would look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*imFEnsEg-epttU7a8-A6Tg.png" /></figure><p>As you can see, rotating by 120° and then applying the “a” reflection (note that the “a” axis has rotated, and is <em>not</em> the axis from point B down vertically), gives the same effect as applying the “b” reflection.</p><p><strong>Factorising Groups</strong></p><p>In maths I’m sure you have come across the concept of factorising. When factorising positive integers, you would usually factorise them into their prime factors.</p><p>For example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*tziaMloiLtq30bZFQj7UeQ.png" /></figure><p>In order to better understand groups, and better understand the Monster Group, we will factorise the group, G, that we have created previously. These factorised groups are called “Simple” groups.</p><p>The first simple group we will make is the rotation group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*BjiA38VCMeSFkW2nR3U0pw.png" /></figure><p>I have called it R since it contains rotations. Now you can think of this as a subset of the main group G, but all simple groups must follow a rule.</p><p>The simple group must be closed. This means that if I combine any element in the group, I should end up with an element that is still within this group.</p><p>For example, if I combine R_120 and R_240, I would get R_0, which is within the group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*x1r0kDku6m0AmC3LXllyOw.png" /></figure><p>Try it yourself, combine any two elements in the R simple group, and you should still get an element that is within the R simple group. There is no way to combine rotations together to get a reflection.</p><p>We can make another simple group here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/1*EBkOT1kBle60CWXTvbNbcA.png" /></figure><p>One thing to note here is that all simple groups must contain the “do nothing” element. You can also see that with S, it follows the previously stated rules.</p><p>You may see that we can write G as a product of R and S:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/91/1*6QannCbJsDO3_CCTTyysBA.png" /></figure><p>What this equation means is that for every element in G, there is some combination of elements in R and elements in S that achieves it. We saw earlier that “a” * R_120 = “b”, and a similar thing can be performed for “c”.</p><p>In one sense, going back to factorising, R and S are like prime factors of G. The “do nothing” element in R and S is what makes them prime. When combining elements, you can think of R_0 as multiplying by 1, as it does not change the operation.</p><p>Using these three groups, the main G group, and the two simple groups R and S, we can describe every symmetry that is able to be performed on an equilateral triangle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*2I8PbgZFLFkUzNmh76BQaQ.png" /></figure><p>This can be done for every single shape in existence, no matter the dimension. There is a theorem called the Classification of Finite Simple Groups, which provides a periodic table of finite simple groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*an7v9zYx6jczdl_iDq3rig.png" /></figure><p>This theorem was proven by over 400 mathematicians, and the proof is between 10,000 and 100,000 pages long.</p><h3>The Monster Group</h3><p>Along with the finite simple groups, there exist a family of groups called the sporadic groups. There are exactly 26 of them. The Monster group is a group that contains a lot of these sporadic groups within it, and the reason it is so famous is because it is so massive.</p><p>The size of the monster, denoted as |M|, is approximately 8 * 10⁵³. This is the number of symmetries contained within the group. Remember that the group for an equilateral triangle has 6 symmetries.</p><p>You may be wondering that, if the shape or object for the group we defined above is an equilateral triangle, what does the object, or rather, structure for the Monster group look like?</p><p>The structure that the Monster group describes exists in a higher dimensional space, a 196,883 dimensional space to be exact. And remember, this has been proven to exist, this behemoth of an entity exists in our universe, which I think is fascinating.</p><h3>Footnote</h3><p>This essay is only surface level knowledge that I have collected from the internet, so don’t take this information as completely true since it may very well be completely incorrect. I would love to fully understand this branch of mathematics further, and if I do, I may write another, updated essay on this, with more detail and actual correct information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9adbfad7eeac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pathfinding methods]]></title>
            <link>https://medium.com/@varadkulk123/pathfinding-methods-553a58a5412b?source=rss-4e436bf8080c------2</link>
            <guid isPermaLink="false">https://medium.com/p/553a58a5412b</guid>
            <category><![CDATA[dijkstra]]></category>
            <category><![CDATA[a-star-algorithm]]></category>
            <category><![CDATA[pathfinding]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[dijkstras-algorithm]]></category>
            <dc:creator><![CDATA[Varad Kulkarni]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 21:27:14 GMT</pubDate>
            <atom:updated>2023-02-24T21:27:14.418Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z4J980133eljHrAP" /><figcaption>Photo by <a href="https://unsplash.com/@and_machines?utm_source=medium&amp;utm_medium=referral">and machines</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Pathfinding methods are widely used in gaming for objects to find their way from one point to another. Objects in these situations usually want to find the fastest route from point A to B. Since the objects can’t “see” and have to be controlled by an algorithm, there are a few ways for an object to navigate a maze, or through obstacles, to get to the other side.</p><p>This has lead to a few algorithms being developed for this, like:</p><ul><li>Dijkstra’s algorithm</li><li>A* algorithm</li></ul><p>These algorithms are frequently used in video games, for character and object pathfinding, but also with satellite navigation systems. Since there are always multiple ways to get from point A to B on a map, there needs to be a very efficient algorithm to find the shortest route, and to make sure that the found route is in fact the shortest.</p><h3>Dijkstra’s algorithm (pronounced dike-stra)</h3><p>As I was doing research for this, I realised how difficult this algorithm is going to be to explain, but I’ll try my best anyway.</p><p>I think this diagram will be useful in explaining:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*5ylQNb4zHPB7AIpZV0YGbg.png" /></figure><p>The goal is to get from A’ to Z, in the shortest time possible. Let’s say the numbers on the routes denote the amount of time it takes to travel that route in minutes. Take a moment yourself to try and find what you think the fastest route would be from A to Z.</p><p>Dijkstra’s algorithm starts at the start point — A — and travels across each route to every node available. In this case, it would start at A and travel to B and C. It keeps track of the minutes required, and puts that number above the node it has travelled to, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*P52dLeBGYpdNQhk-EI8HzA.png" /></figure><p>As you can see, A is now done, so we colour it in red just so we can remember it is completed. Right now, the diagram looks very simple, so let’s continue the behaviour of the algorithm with the next smallest node value, which is C:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*Rr8vd3v9NV9KVoPQ5Ftknw.png" /></figure><p>As you can see, when the C node travels to the B node, the total is 2 + 1 = 3, which is less than 4.</p><p>According to the algorithm, we keep the lowest total value. This ensures we get the quickest time to get to each node, and therefore get the quickest time to get to the end node. As you can see, A → C → B is faster than A→ B.</p><p>Next is node B, since it has the next lowest value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*dJ1yM0LJgRWg285LDn-MDA.png" /></figure><p>Again, the total time from A → C → B → D is 8, which is less than 10, so we replace it with the lower value. Note that node B can only go to node D since every other node that the routes from B lead to are completed (shaded in red).</p><p>Now to node D:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*eKh2M6oEGL_oWOOAZq5SnA.png" /></figure><p>In this case, we get a lower total time for node E, so we replace the value. You may also notice that we have reached node Z, but we have not completed all the nodes, so the algorithm still keeps going, to ensure it has found the shortest route.</p><p>Now the only node remaining is node E:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*9RSoTYAHqt_qGEB8pnQk6Q.png" /></figure><p>As you can see, the route from E → Z is 15 minutes long, which is higher than the value that Z already has, so it is not written down. I have illustrated it here for clarity.</p><p>Now, we have completed every node (apart from the end node), and we have gotten the lowest total time to reach the end node — 14.</p><p>And now the algorithm backtracks through the nodes needed to reach node Z from node A.</p><p>Therefore, the shortest route form node A to Z is A → C → B → D → Z, and takes 14 minutes.</p><p>As you can see, using this algorithm ensures that the found route is the shortest, since it is effectively searching through every possible route, but only taking note of the shortest paths.</p><p>You may wonder what happens if there is a node which cannot be reached by any other node, a node that is not connected via any routes.</p><p>Well, generally, every node is given a value of infinity at the start so that, when the route is found, the algorithm can tell if it is possible or not to get to each node. If the time value is infinite, then it is going to be more than any other value, so it automatically gets replaced if a route goes to it, but does not get replaced if no route leads there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*sotZl0IMXBBWtvddPPk5Nw.png" /></figure><p>As you can see, if we now start at A, B will again be replaced with 4, and C will be replaced with 2, as before. However, F will never be replaced by anything since there are no routes that lead to it.</p><p>The algorithm also keeps track of the pathing it used to get to a node, and replaces that pathing if it needs to replace the node value, so that it knows how to backtrack at the end, when it has reached the finish point.</p><p>However, as efficient and useful as this seems, there is one problem with Dijkstra’s algorithm. If we wanted to implement this algorithm for satellite navigation, we would have hundreds of thousands of nodes, with roads being the routes that connect the nodes. If we wanted to get from one point to another, let’s say from Edinburgh to Glasgow, we would obviously want to head west, instead of going any other direction. However, this algorithm would still search every single direction, instead of looking near the direction you want to travel. With a simple and small example like this, it is alright if the algorithm checks every route, but you don’t want that to happen with a massive node system, since that would make the navigation system very slow at finding a route.</p><h3>A* algorithm (pronounced A star)</h3><p>This algorithm is a variation of Dijkstra’s and it improves on the efficiency of it. From above, you can see that one fall-back of Dijkstra’s is that it has to search every single path before it finished. With this one, while there is more to keep track of, it stops once it has reached the end, and it does not need to complete every node to check if the found route is the shortest. I am going to be using a different node map to better illustrate my point.</p><p>Firstly, we can run Dijkstra’s algorithm to get the path which we know is going to be the shortest. In fact, take some time to work through the algorithm yourself with a pen and paper, and check what your answer is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*7namPtmMedh7Zrj4dbTVsg.png" /></figure><p>Alright so with Dijkstra, the fastest route is A → C → F → H → Z. However, you can see that you have to process each path possible to get to $z$, which takes time. Of course, this would only be a difference of a few milliseconds for a computer, but think of how much longer it would take if we were looking at a much bigger scale, like getting from Edinburgh to Glasgow as mentioned above.</p><p>Now to explain A*. Firstly, I’ll explain what things we need to keep track of.</p><p>In order for A* to understand the general direction it should be travelling, we need to note down the actual physical distance between each node, and the end node:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*2mLKNXJiti9S6zNidpakbQ.png" /></figure><p>Here, I have noted down the actual distance in dark blue, measured in centimetres. For example, the direct distance between node E and the end node is 7cm. The distance from Z to the end node (Z) is obviously 0, so we do not need to note that down, and the distance from the start node to the end node does not matter because we will not need to use it, as you will see.</p><p>Now, we start from the start node, as we did for Dijkstra, but instead of just adding up the route value, we also add the distance value. I have noted the final node value in green:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*Qgk4O8UjqzPmSs_XMQP5rQ.png" /></figure><p>The letter in the brackets is just to remind us of the path that was taken to get to the node. Since we have only completed node A, both node values have the path A. Node B has the value 16 since we add up the route distance and also the direct distance → (4) + 12 = 16.</p><p>Again, like Dijkstra, we continue from the next lowest node value, so now onto node B:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*GxCT4bE_oA2qGlaL9aE-ig.png" /></figure><p>We again add the route values, and also the distance value. For example, from B → C, the value would be (4 + 11) + 11 = 26. Since this is higher than the value of 19 that we have, we do not replace it. Next in the stack is node C, since it has the value 19. Since it has the current path from node A, we use that path to continue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*qciZsokCR6yCwFG9xQeE-w.png" /></figure><p>As you can see, node E becomes (8 + 7) + 7 = 22, and node F becomes (8 + 1) + 8 = 17. Note that node C cannot travel to node B since it is completed. The next lowest node value is node F with a value of 17:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*sTfKRtuStuXfbcvoBcH9OA.png" /></figure><p>Node F can only travel to two nodes. If we go to node E, the total value would be (8 + 1 + 6) + 7 = 22, which is the same value as before, so we don’t need to replace it. If we go to node H, the total value would be (8 + 1 + 2) + 5 = 16, which is now the next lowest node value, so node H is next in the stack:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*p-j3QCbmaLd18Q2BlfpgNQ.png" /></figure><p>Node H can travel to three different nodes. When travelling to node D, the total would be (8 + 1 + 2 + 4) + 8 = 23, which is higher than the current value, so we do not replace it. The next node that can be travelled to is G, which has a total of (8 + 1 + 2 + 14) + 4 = 29. And the last node is the end node. The value for this node is (8 + 1 + 2 + 10) + 0 = 21, however the value does not matter since we have reached the end of the required path.</p><p>Dijkstra’s only stops when every node is marked as completed, however, A* can stop when the end node is reached for the first time. From this, we can backtrack using the letters in the brackets to know where to backtrack to. From node Z, we go to H, then to F, then to C, and finally to A, the start node.</p><p>Therefore, the final and shortest path using the A* algorithm is A → C → $f$ → H → Z, as we calculated with Dijkstra.</p><p>As you can see, not every node needed to be processed. Nodes D, E, and G were left unprocessed which might not seem like much, but could be huge on a larger scale. Keeping track of the actual values from the end goal helps the algorithm to know that it is going in the right direction since, as it gets closer to the end, the total node values decrease, which the algorithm then prioritises to process first, which leads to it finding the end quicker.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=553a58a5412b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Collatz Conjecture]]></title>
            <link>https://medium.com/@varadkulk123/the-collatz-conjecture-68130a357486?source=rss-4e436bf8080c------2</link>
            <guid isPermaLink="false">https://medium.com/p/68130a357486</guid>
            <category><![CDATA[collatz]]></category>
            <category><![CDATA[collatz-conjecture]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[paul-erdos]]></category>
            <dc:creator><![CDATA[Varad Kulkarni]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 21:12:06 GMT</pubDate>
            <atom:updated>2023-02-25T17:25:40.042Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RN7JLoG_n5UCIFI0" /><figcaption>Photo by <a href="https://unsplash.com/@dancristianpaduret?utm_source=medium&amp;utm_medium=referral">Dan Cristian Pădureț</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>A delineation</h4><h3>Explaining the conjecture</h3><p>The collatz conjecture was derived by Lothar Collatz. It states that every number eventually arrives at 1 if you apply the following rules:</p><ol><li>If the number is odd, times it by 3 and add 1</li><li>If the number is even, divide it by 2</li></ol><p>That’s it.</p><p>This may seem like a simple problem, and it is. You could explain this to children and they would understand. However, the conjecture has neither been proven nor disproven.</p><p>Try it yourself, take any number and apply the rules to it. You will eventually end up at 1, which is odd, so you multiply by 3 and add 1–4. You then divide by 2–2, then divide by 2 again — 1. You enter a loop of 4 → 2 → 1 → 4 → 2 etc.</p><p>For example, suppose we start at 7. We then go to 7 * 3 + 1 = 22, then to 11, then to 34, and so on. Here is the route for 7:</p><p>7 &gt; 22 &gt; 11 &gt; 34 &gt; 17 &gt; 52 &gt; 26 &gt; 13 &gt; 40 &gt; 20 &gt; 10 &gt; 5 &gt; 16 &gt; 8 &gt; 4 &gt; 2 &gt; 1</p><p>And, if you take an adjacent number, let’s say 6, you get:</p><p>6 &gt; 3 &gt; 10 &gt; 5 &gt; 16 &gt; 8 &gt; 4 &gt; 2 &gt; 1</p><p>A distinctly shorter route.</p><p>The number of points that each number goes through are called nodes. The number 7 has 17 nodes, and the number 6 has 9 nodes.</p><p>Here is a graph for the first 10 numbers, with the number of nodes required to reach 1 on the vertical axis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*mbjPkQLnxwqWwGan9nEkpQ.png" /><figcaption>Line graph of the first 10 numbers, with the number of nodes required to reach 1 on the vertical axis</figcaption></figure><p>As you can see, there isn’t really a solid pattern to it. It is very jumpy and seemingly random, however, there are solid rules to generate those numbers.</p><p>This seemingly somewhat interesting conjecture is actually… pretty useless. No use has been found for the Collatz Conjecture in mathematics, and it still remains unsolved. There are people who have wasted their lives on this problem, and gotten nowhere. In fact, Paul Erdős (one of the most prolific mathematicians in the 20th century) has said that</p><blockquote>“Mathematics is not yet ripe enough for such questions”</blockquote><h3>My program</h3><p>Since this is a problem with repetition, I obviously made a program. I wrote code to generate the node values for the first 500000 numbers.</p><p>Unsurprisingly, the minimum nodes are 0, for number 1 since it is already at 1, and does not need to progress further.</p><p>The maximum nodes are for the number 410011, with a node value of 448. This means the number 410011 goes through 448 other numbers before it too eventually falls to one.</p><p>I put the node values in a list, which makes it easy to make a graph like the one above for the numbers from 1 to 500000:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*m4v5r4pDsNTpZ12Bel_fbA.png" /><figcaption>Line graph of the first 500000 numbers, with the number of nodes required to reach 1 on the vertical axis</figcaption></figure><p>Again with the node values on the vertical axis, and the starting numbers on the horizontal axis.</p><p>As you can see, this looks very messy and very random. And it is, or at least, it is pseudorandom.</p><p>You can see my code <a href="https://github.com/Hades62442/collatz">here</a>.</p><h3>Negative numbers</h3><p>All numbers eventually fall to 1, and are stuck looping from 4 to 2 to 1 and back to 4. We can visualise this by drawing a tree diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*aiuHhxStEFJvy9uV.jpeg" /><figcaption>Tree diagram of various numbers, all leading down to 1</figcaption></figure><p>We can see from this that there is only one “branch” that all numbers are a part of — that we know of. Every number up to 1*10¹⁸ (that’s a quintillion) and they all fall to 1 eventually, so we can be sure that there is only one branch. However, what happens if you apply this rule to negative numbers?</p><p>Let’s start with -7:</p><p>-7 &gt; -20 &gt; -10 &gt; -5 &gt; -14 &gt; -7</p><p>It’s a loop.</p><p>How about -2?</p><p>-2 &gt; -1 &gt; -2</p><p>Another loop, a little similar to the positive numbers.</p><p>The third loop for negative numbers starts with -17, and has 19 nodes before it loops back around to -17.</p><p>This gives us a total of 5 loops that integers can end up in:</p><ol><li>1 &gt; 4 &gt; 2 &gt; 1</li><li>7 &gt; -20 &gt; -10 &gt; -5 &gt; -14 &gt; -7</li><li>1 &gt; -2 &gt; -1</li><li>17 &gt; -50 &gt; -25 &gt;… &gt; -34 &gt; -17</li><li>And of course, 0 &gt; 0 &gt; 0</li></ol><p>Of course, it is not proven that these are the only 5, but is more of a general statement of the Collatz Conjecture.</p><p>Try it yourself, pick any integer, and see which loop it ends up in.</p><h3>Conclusion</h3><p>Overall, the Collatz Conjecture is an interesting problem, which looks easy when first viewed. However, as you delve deeper into it, it becomes increasingly complex and intriguing. Since so many numbers have been tested, and they all follow the conjecture, it seems futile to work on proving the problem. But maybe we should be trying to disprove the theorem instead of spending so much time on trying to prove it?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68130a357486" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ability generation methods in Dungeons and Dragons]]></title>
            <link>https://medium.com/@varadkulk123/ability-generation-methods-in-dungeons-and-dragons-3753f9fdd61b?source=rss-4e436bf8080c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3753f9fdd61b</guid>
            <category><![CDATA[dungeons-and-dragons]]></category>
            <category><![CDATA[graphs-are-fun]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[dice]]></category>
            <dc:creator><![CDATA[Varad Kulkarni]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 20:54:40 GMT</pubDate>
            <atom:updated>2023-02-24T20:54:40.297Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3eHKDHqOk0UsGBYT" /><figcaption>Photo by <a href="https://unsplash.com/@lucrin?utm_source=medium&amp;utm_medium=referral">Gian-Luca Riner</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>An analysis</h4><p>Dungeons and Dragons is a great tabletop roleplaying game, which requires a lot of dice. In DnD, you use dice for a lot of things, making an attack, determining strength, telling how perceptive you are, and even seducing a dragon. This adds a lot of randomness and chance to the game.</p><p>When making a roll, you usually have a modifier, something to add or subtract from your dice roll. This can be up to +5 or down to -4 (without any other bonuses). These modifiers are determined by something called ability scores.</p><p>There are six main ability scores:</p><ul><li>Strength — how strong your character is</li><li>Dexterity — how dextrous your character is</li><li>Constitution — how healthy your character is</li><li>Intelligence — how intelligent your character is, book smarts</li><li>Wisdom — how wise your character is, street smarts</li><li>Charisma — how charismatic your character is</li></ul><p>There are several more abilities in DnD, but those scores are determined by these 6 main scores, and also a few proficiencies you may get from race or class bonuses.</p><p>When generating these 6 scores, you have a few different options on how to do so. Since they are the main scores, players generally want them to be as high as possible. The ways of generating ability scores are usually decided by the DM.</p><p>In this essay, I will go through a few generation methods, and show the statistics on them. If they are skewed to the high or low side, how effective they are, and other interesting quirks that I found.</p><h3>1. Standard</h3><p>The standard method for DnD ability score generation is rolling 4d6, dropping the lowest roll, and then totalling the remaining dice. For example, if you rolled</p><blockquote>3, 4, 6, 2</blockquote><p>You would drop the 2 and get 13 as your ability score (3 + 4 + 6).</p><p>I initially wanted to write each possible roll for 4d6, remove the lowest, and get the total that way, but I quickly realised how long and tedious that would get. So, I instead did 4d3 as an example, and wrote a program to generate the rolls for 4d6.</p><p>This was the monstrous table of rolls for 4d3:</p><figure><img alt="Table of possbilities of rolls with 4 3-sided dice. The lowest rolls are highlighted in red and the result of removing the lowest, and adding the remaining dice is highlighted in green." src="https://cdn-images-1.medium.com/max/602/1*Q4luEY4HEw36whhCv7AOKw.png" /><figcaption>Table of rolls for 4d3. Red highlights the removed roll, and green highlights the total of the roll.</figcaption></figure><p>The red is the lowest roll, to be removed, and the green are the totals.</p><p>As you can see, even with 4d3, there is a lot of possible combinations, a total of 81 possible rolls.</p><p>This then allowed me to make a table and graph for the rolls:</p><figure><img alt="Histogram of results for rolling 4d3 using standard method. Peak at 7, and lowest point at 3." src="https://cdn-images-1.medium.com/max/481/1*sMzxn5ZSMJsdCijKlGVI5Q.png" /><figcaption>Histogram of results for 4d3, standard method</figcaption></figure><p>From this, you can see that the frequency of getting very low numbers is low, but it increases for the higher numbers. The maximum is 9, and the minimum is 3, and you can see the disparity between the frequency in each roll.</p><p>The most common roll is a seven, which is also, incidentally, the most common roll for 2d6.</p><p>From here, I decided to write a program to generate the rolls for 4d6, find and remove the lowest, and get the totals. Then it counts how many of each total occur (for example, how many 3s, 4s, etc.)</p><p>Here are the results:</p><figure><img alt="Histogram of results for rolling 4d6 using standard method. Peak at 13, and lowest point at 3." src="https://cdn-images-1.medium.com/max/511/1*Lzg-hD2_dIt1t-uTXx7-1A.png" /><figcaption>Histogram of results for 4d6, standard method</figcaption></figure><p>As you can see, the number of rolls very rapidly increases since 4d6 has 1296 possible combinations.</p><p>This time, 13 is the most common roll, with 12 with a close second. 13 had a frequency of 172, and 12 has a frequency of 167. We can also again see that it is more difficult to roll 3s and 4s, but the frequencies increase as we get towards 13, then decrease again, but still stay quite high.</p><p>The median of these rolls is 13, and the mean is 12.2. This means the data is negatively skewed since mean &lt; median.</p><p>For this method, the chance of generating the lowest number possible (3) is 0.077%.</p><p>The chance of generating the highest number possible (18) is 1.62%.</p><h3>2. Classic</h3><p>Another very common method for generating ability scores is the classic method. In the classic method, you roll 3d6, and take that as your ability score.</p><p>I again wrote a program to generate all the possible rolls and find the totals, instead of writing them by hand.</p><p>Here is the data:</p><figure><img alt="Histogram of results for rolling 3d6 using classic method. Peak at 10 and 11, and lowest point at 3 and 18" src="https://cdn-images-1.medium.com/max/511/1*yoKF9zRXHaS3zQeRJfmvOw.png" /><figcaption>Histogram of results for 3d6, classic method</figcaption></figure><p>This is a fully symmetric graph, with both 10 and 11 being the peaks. The graph increases and decreases uniformly, producing a perfect bell curve. It makes sense why it is a perfect curve, since it is just pure rolls, nothing to vary or change the results.</p><p>For this method, the chance of generating the lowest possible number (3) is 0.46%.</p><p>This is also the percentage chance for generating the highest possible number (18).</p><h3>3. Heroic</h3><p>This generation is a little more uncommon since it doesn’t work well for balanced and generic campaigns. This is more for one-shots or similar if you want more powerful characters.</p><p>For this method, you roll 2d6 and then add 6 to get your final score. As you may be able to tell, this boosts the scores quite a bit. The maximum is 18 and the minimum is 8 with this method.</p><p>Here is the data:</p><figure><img alt="Histogram of results for heroic method. Peak at 13, and lowest point at 8 and 18." src="https://cdn-images-1.medium.com/max/446/1*UvKv8X7oFK21ZUwVsnrdMQ.png" /><figcaption>Histogram of results for 2d6+6, heroic method</figcaption></figure><p>This is also perfectly symmetrical, with 13 being the peak. Again, it is clear why the graph is symmetric since there is nothing to vary the totals. There are 36 data possible rolls for this generation type.</p><p>The chance of generating the lowest possible number (8) using this method is 2.7%.</p><p>This is also the percentage chance for generating the highest possible number (18).</p><h3>4. Other methods</h3><p>There are two other methods which are sometimes used, but I haven’t calculated data for.</p><p>The first is called dice pool.</p><p>Each player has a pool of 24d6 to assign to their scores and decides how many d6 to use for each score, with a minimum of 3d6. After deciding how many dice to roll for each score, the player rolls them and takes the total of the 3 highest dice as their ability score.</p><p>For example, if 5d6 were assigned to Strength, and</p><blockquote>2, 4, 1, 5, 6</blockquote><p>Was rolled, you would take 15 as your ability score (4 + 5 + 6)</p><p>The second method is called purchase.</p><p>Each player gets a number of points to spend on increasing their ability scores. Each score starts at 8. It costs 1 point to increase the score by one and the player gains 1 point if they decrease their score by one.</p><p>The reason I have not calculated the data and made graphs for these two methods is because there are too many factors, too many variables that can change things. I feel like there would be too many things to handle, although I may do it at a later time.</p><h3>Conclusion</h3><pre>+----------+-------------+------------+--------------------+<br>|          | Min chance  | Max chance | Most common chance |<br>+----------+-------------+------------+--------------------+<br>| Standard | 0.0077% (3) | 1.62% (18) | 13.27%(13)         |<br>| Classic  | 0.46% (3)   | 0.46% (18) | 12.5% (10 or 11)   |<br>| Heroic   | 2.7% (8)    | 2.7% (18)  | 16.7% (13)         |<br>+----------+-------------+------------+--------------------+</pre><p>From this, we can see that the best method for generating the highest scores is, obviously, heroic. It has a chance of 2.7% of generating an 18, which is the highest out of the three methods. It also has a 2.7% chance of generating the lowest and, while that may seem high, remember that the minimum for the heroic method is 8, as opposed to 3 for the other two methods.</p><p>Heroic also has the highest chance of generating the most common value of 13.</p><p>Classic is the worst method of generating ability scores, out of the three since it has the lowest chance of generating an 18 at 0.46%. That’s less than half a percent, albeit there is the same chance for generating the lowest possible score of 3, so maybe it has its advantages.</p><p>Classic also has the lowest chance of generating the most common value of 10/11 at 12.5%. It has a 9.72% chance of generating a 13, which is the most common for the other two methods, which is even worse.</p><p>Standard method does seem to be the most balanced, which explains why it is the most widely used and called the “standard” method.</p><h3>Evaluation</h3><p>Now that I am looking back, the generation method for getting all possible rolls could be skewed or incorrect. I’ll explain how the code works to generate it.</p><p>Using the 4d6 example, I start with 4 variables which all have a value of 1.</p><p>I add that list to a big list, then check if the last variable is less than 6. If it is, increment it by one.</p><p>If not however, I then check if the second last variable is less than 6. If it is, increment it by one and also set the last variable to 1.</p><p>If it is not, check if the second variable is less than 6. If it is, increment it by one and also set the second last <em>and</em> last variable to 1.</p><p>If it is not, check if the first variable is less than 6. If it is, increment it by one and also set all other variables to 1.</p><p>If it is not, it means that all variables should be at 6, which means all combos have been accounted for. This then makes the code set a variable to True.</p><p>Then loop back to the start, where it appends the four variables as a list to the big list. It then repeats this process until the variable is set to True.</p><p>At first, I made the mistake of only setting the next variable to 1 instead of all of the ones after. For example, if the code incremented the second variable, it would only set the third to 1, and leave the fourth alone. This caused me to not have the correct amount of data and so I had to redo parts of it.</p><p>The reason why this could be an incorrect method of generating rolls is because it treats the roll</p><blockquote>1, 2, 3, 4</blockquote><p>The same as</p><blockquote>1, 3, 2, 4</blockquote><p>And also the same as</p><blockquote>3, 1, 4, 2</blockquote><p>And so on</p><p>I don’t know if that is correct or not, since its technically the same roll but also each die is independent of each roll and every other die.</p><p>Thank you very much for reading. Please let me know of any changes and criticisms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3753f9fdd61b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>