<?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 Ian Chau on Medium]]></title>
        <description><![CDATA[Stories by Ian Chau on Medium]]></description>
        <link>https://medium.com/@ianchau379?source=rss-e5c3ec00ad25------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*V9L-0rAdkjS1OduI5IF3ow@2x.jpeg</url>
            <title>Stories by Ian Chau on Medium</title>
            <link>https://medium.com/@ianchau379?source=rss-e5c3ec00ad25------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 14:54:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ianchau379/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[Some thoughts on UNO: No Mercy & the Liar’s dice]]></title>
            <link>https://medium.com/@ianchau379/some-thoughts-on-uno-no-mercy-the-liars-dice-de073d6de592?source=rss-e5c3ec00ad25------2</link>
            <guid isPermaLink="false">https://medium.com/p/de073d6de592</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[gambling]]></category>
            <category><![CDATA[board-games]]></category>
            <dc:creator><![CDATA[Ian Chau]]></dc:creator>
            <pubDate>Mon, 21 Jul 2025 20:08:25 GMT</pubDate>
            <atom:updated>2025-07-21T20:08:25.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qq66mKmHstIDTvuD" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EC7CfSwYTk0H-47l" /></figure><p>I want to write a quick note about the EV perspective on both games.</p><h3>UNO: No Mercy</h3><p>In UNO: No Mercy, a player will be eliminated for having 25 or more cards in their hand. Like the typical UNO, there are DRAW cards, but one type of DRAW card draw my attention — <strong>Wild Color Roulette</strong> — when placed, the next player chooses a color and draws cards from the draw pile until they reveal a card of that color. Unlike other DRAW cards, the number of cards drawn is not fixed.</p><p>So, <em>“What is the expected number of cards drawn?”</em>.</p><p>Equivalently, we ask <em>“On the average, how far from the top will the first card with the matching color be?”</em>. This is a similar question where I had discussed in a previous blog post.</p><p><a href="https://medium.com/@ianchau379/another-way-to-the-first-ace-problem-1a2737062383">Another way to the First Ace Problem</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnHK9-fFU6pQGOiq-ClcYA.png" /><figcaption>Table from <a href="https://www.coololdgames.com/card-games/shedding/uno/show-em-no-mercy/">coololdgames</a> by Paul Dunlop</figcaption></figure><p>Since we have 24 uncolored cards and 140 colored cards (4 colors of red, green, yellow and blue equally distributed), for a given color we know there are 35 cards in the whole deck. Based on method 1 estabilished in my <a href="https://medium.com/@ianchau379/another-way-to-the-first-ace-problem-1a2737062383">blog post</a>, the expected number of cards drawn is (164–35)/(35+1) + 1 = <strong>4.5833</strong>.</p><p>We used the whole deck above, but at any point of the game we can roughly assume the remaining deck distributed just like the whole deck shuffled randomly (i.e. ~14.6% uncolored, ~21.3% for each color). Then, we can roughly expect 4–5 draws for a card with the matching color.</p><p>Moreover, one may wants to strategically pick the color to reduce the chance of large draw. I think the best one can do is to integrate all the information in memory and deduce the majority of colors remaining in the deck. In case someone used the “discard all” card, record the number of cards removed from his hand to help yourself count the remaining cards of the same color still in the pile.</p><h3>Liar’s dice</h3><p>In what follows, I will refer to the Liar’s dice rule in most HK’s bar (香港大話骰) where <strong>1 can be treated as any number</strong> and there is no restriciton to have at least two numbers in the 5 dice same.</p><p>In fact, the restriciton poses minimal effect, because over 90% cases 2 out of 5 dices are the same. So, I will just abandon it.</p><p><strong>Baseline</strong>: In an <em>N</em>-player game, we can assume 1,2,3,4,5,6 are uniformly distributed, the expected total count of dice with 1 face up is <strong>5<em>N</em>/6</strong>. The expected total count of dice with 1 and 2 face up is <strong>10<em>N</em>/6</strong> (Recall: 1 can be treated as any number). Hence, for <em>N</em> = 5, one can expect ~4.17 ones and ~8.33 other numbers in the total of 25 dice.</p><p>Some reasonable blindfolded starting calls can be:<br>Very conservative: “2 ones” (兩個一), “4 fives” (四個五).<br>Fair: “5 ones” (五個一), “8 fives” (八個五).<br>More aggressive: “6 ones” (六個一), “10 fives” (十個五).</p><p><strong>Incorporate your range</strong>: Conditional expectation is easy to calculate because the face number of each dice is independent. Given the number of <em>i </em>(for <em>i</em> = 1,2,3,4,5,6) in your dice cup is <em>k(i)</em>, the expected total count of dice with 1 face up is 5*(<em>N</em>-1)/6 + <em>k(1)</em>. Hence, for <em>N</em> = 5, one can expect ~3.33+<em>k(1)</em> ones and ~6.67+<em>k(1)+k(j) </em>other number <em>j</em>.</p><p>For example, your 5 dice are 1 2 2 4 6. Then, <em>k(1)</em> = <em>k(4)</em> = <em>k(6)</em> = 1, <em>k(2)</em> = 2. The expected total count of dice with 1 and 2 face up is 10*(5-1)/6 + <em>k(1) </em>+ <em>k(2)</em> = 9.67. Calling “9 twos” (九個二), “10 twos” (十個二) may sound a little intimidating to others in disbelief which might tempt them to open the dice cup, but you know you have a good chance of winning. Ofc, this affirmation should better combined with some strategies to understand other players’ range.</p><p><strong>Incorporate other players’ range</strong>: Liar’s Dice is an incomplete information game. Practically, you want to get a sense of what dice others got to determine whether to open the dice cup or make another call. While listening to other people’s calls, you can infer what they got, but as the game name suggests players tell lies time to time. This kind of information are less valuable or creditable.</p><p>On the other hand, I think it’s more informative that the next player accepted the previous player’s call when the previous player make a call above baseline level, because there is literally almost no incentive to not decline when a player is so sure that the call is invalid. The fact that a player refused to open the dice cup, implies he/ she may got some of that dice number in his/ her cup. This can further be validated if the player continue calling the same number. Otherwise, the player called another number, he/ she must got a lot of that dice number in his/ her cup, because he/ she decided to make a stronger claim than to have accepted a weaker offer that is already considered risky to the previous player.</p><p>Example: In a 5-player game, if a player believes “11 fives” much more than he/ she doesn’t believe in “10 threes” the previous player offers. The player cannot confidently reject that there are 10 threes, he/ she can even more confidently claim an 11 fives shows that the player got some 1s, perhaps more than 2, or really a lot of 5s.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de073d6de592" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Functions with standard input and output]]></title>
            <link>https://medium.com/@ianchau379/testing-functions-with-standard-input-and-output-5377299ae8d5?source=rss-e5c3ec00ad25------2</link>
            <guid isPermaLink="false">https://medium.com/p/5377299ae8d5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Ian Chau]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 17:54:24 GMT</pubDate>
            <atom:updated>2025-06-30T17:54:24.792Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently ran into a problem while trying to automate unit testing for a function that paused, mid-execution, waited for a user to input some value, and then print the result in the console. I was looking for a way where I can mimic a user input and capture the output into a variable that I could compare in my tests.</p><p>In this article, I will discuss serveral ways I found. For example, I have the following calculator function in example.py that accepts 3 user inputs (first integer, second integer and an operator) and print a calculated result or an error statement. How to test the function’s logic with some established cases?</p><pre>def calculator():<br>    try:<br>        x1 = int(input()) # Enter first integer<br>        x2 = int(input()) # Enter second integer<br>        operator = input() # Enter an operator (+, -, *, /)<br><br>        if operator == &#39;+&#39;:<br>            res = x1 + x2<br>        elif operator == &#39;-&#39;:<br>            res = x1 - x2<br>        elif operator == &#39;*&#39;:<br>            res = x1 * x2<br>        elif operator == &#39;/&#39;:<br>            if x2 == 0:<br>                print(&quot;Error: Division by zero is not allowed.&quot;)<br>                return<br>            res = x1 / x2<br>        else:<br>            print(&quot;Error: Invalid operator. Please use +, -, *, or /.&quot;)<br>            return<br>        <br>        print(f&quot;{res:.2f}&quot;) # Print the result formatted to 2 dp<br><br>    except ValueError:<br>        print(&quot;Error: Invalid input. Please enter numeric values.&quot;)</pre><h4>Using Subprocess</h4><pre>input_data = &quot;1\n2\n-&quot;<br>output_res = &quot;-1.00\n&quot;<br>result = subprocess.run([&#39;python&#39;, &#39;example.py&#39;], input=input_data, text=True, capture_output=True)<br>print(result.stdout==output_res) # Output: True (1-2=-1.00)</pre><p>With Subprocess Module, you can call external program in python and capture the output of those commands. The subprocess runs independently of your main script, meaning it can fail or encounter issues without affecting the execution of the main script. Also, subprocess.run() is <strong>a blocking call</strong>, so the main will wait until it completes and returns a <a href="https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess">CompletedProcess</a> instance.</p><h4><a href="https://napsterinblue.github.io/notes/python/development/sim_stdin/">Overwriting </a><a href="https://napsterinblue.github.io/notes/python/development/sim_stdin/">sys.stdin</a></h4><pre>input_data = &quot;117\n0\n/&quot;<br>output_res = &quot;Error: Division by zero is not allowed.\n&quot;<br>with StringIO(input_data) as i, StringIO() as o<br>      stdin = sys.stdin<br>      stdout = sys.stdout<br>      sys.stdin = i<br>      sys.stdout = o<br>      calculator()<br>      sys.stdin = stdin<br>      sys.stdout = stdout<br>      output = o.getvalue()<br>print(output==output_res)</pre><p>The standard input() in Python is built upon sys.stdin.readline(), this is also why it accepts a single line input. The sys.stdin is an instance of TextIOWrapper, which allows for reading text input. If we inspect the class hierarchy, we will find that TextIOWrapper and StringIO share the same base class of _io.IOBase. This means that both can be treated as <a href="https://www.pythonmorsels.com/file-like-objects-in-python/">file-like objects</a>, similar to how we handle files opened with open(file, mode).</p><p>The above design <strong>redirect</strong> the destination where input() and print() listen to by default (i.e. terminal/ concole) into StringIO. This enables us to treat strings as a stream of text I/O. By doing so, we can capture output generated by the print() function while simultaneously simulating user input for the input() function. We can then retrieve the output and restore the input() and print() destination to the default ones.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5377299ae8d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Triangular Arbitrage Explained (a naive algorithm)[part 1]]]></title>
            <link>https://medium.com/@ianchau379/triangular-arbitrage-explained-a-naive-algorithm-part-1-2e82d063ae4f?source=rss-e5c3ec00ad25------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e82d063ae4f</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[arbitrage]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Ian Chau]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 20:13:20 GMT</pubDate>
            <atom:updated>2025-07-21T18:51:49.905Z</atom:updated>
            <content:encoded><![CDATA[<h3>Triangular Arbitrage Explained (a naive algorithm)</h3><p>Suppose you have real time quotes for three assets, that provide you with three bid prices and three ask prices¹.</p><p>Define assets = {usd, BTC, ETH}</p><p>For example, you were given:</p><figure><img alt="bid ask
 1 BTC can exchange 90000 us, 90034 usd can exchange 1 BTC.
 1 ETH can exchange 2000 usd, 2002 usd can exchange 1 ETH.
 1 BTC can exchange 45.470 ETH, 45.478 ETH can exchange 1 BTC." src="https://cdn-images-1.medium.com/max/1024/1*qfcZmjAdKgi7kpSTkrxE_Q.png" /><figcaption>A two-way quote for defined assets</figcaption></figure><p>You may format the price data as a 2d array.</p><p>Then [<em>i</em>][<em>j</em>] entry of the 2d array shows how many units of assets[<em>j</em>] can be brought with 1 unit of assets[<em>i</em>].</p><pre>[<br>  [1,      0.0000111069,  0.0004995 ], // USD to USD, BTC, ETH<br>  [90000,  1,             45.470    ], // BTC to USD, BTC, ETH<br>  [2000,   0.021988653,   1         ]  // ETH to USD, BTC, ETH<br>]</pre><p>In this situation, there are two ways to conduct triangular arbitrage <strong>in usd standard</strong>, mainly:</p><ol><li>usd → BTC → ETH → usd</li><li>usd → ETH → BTC → usd</li></ol><p>Let’s work them out by hand. You have $<em>M</em>.</p><p>For (1), you turn $<em>M</em> into 0.000011106×<em>M</em> BTC. <br>Then, exchange all you BTC for 45.470×0.000011106×<em>M</em> ETH. <br>Finally, exchange all your ETH to $2000×45.470×0.000011106×<em>M</em>. <br>In summary, you turn $<em>M</em> into $1.01<em>M</em>, gives 1% profit.</p><p>For (2), you turn $<em>M</em> into 0.0004995×<em>M</em> ETH. <br>Then, exchange all your ETH for 0.021988653×0.0004995×<em>M</em> BTC. <br>Finally, exchange all your BTC to $90000×0.021988653×0.0004995×<em>M</em>. <br>In summary, you turn $<em>M</em> into $0.99<em>M</em>, this gives 1% loss.</p><p>We lay a general algorithm to determine triangular arbitrage opportunities in case there are only three assets.</p><pre>def detect_triangular_arbitrage(mat, i=0):<br>    &#39;&#39;&#39;<br>    Signal triangular arbitrage opportunity<br><br>    mat: A 3 by 3 array representing the price relations of the three assets.<br>    i  : An index (0, 1, or 2) indicating the domestic currency or the standard currency used for comparison. <br>    &#39;&#39;&#39;<br>    arbitrage_found = False<br>    initial_amount = 1  # Starting with 1 unit of the domestic currency<br><br>    # Check path 1: A → B → C → A<br>    final_amount1 = (<br>        mat[i][(i + 1) % 3] * <br>        mat[(i + 1) % 3][(i + 2) % 3] * <br>        mat[(i + 2) % 3][i]<br>    )<br>    if final_amount1 &gt; 1:<br>        profit_percentage1 = (final_amount1 - initial_amount) / initial_amount * 100<br>        print(f&#39;Arbitrage opportunity found via route: {i} --&gt; {(i + 1) % 3} --&gt; {(i + 2) % 3} --&gt; {i}&#39;)<br>        print(f&#39;Profit Percentage: {profit_percentage1:.2f}%&#39;)<br>        arbitrage_found = True<br><br>    # Check path 2: A → C → B → A<br>    final_amount2 = (<br>        mat[i][(i + 2) % 3] * <br>        mat[(i + 2) % 3][(i + 1) % 3] * <br>        mat[(i + 1) % 3][i]<br>    )<br>    if final_amount2 &gt; 1:<br>        profit_percentage2 = (final_amount2 - initial_amount) / initial_amount * 100<br>        print(f&#39;Arbitrage opportunity found via route: {i} --&gt; {(i + 2) % 3} --&gt; {(i + 1) % 3} --&gt; {i}&#39;)<br>        print(f&#39;Profit Percentage: {profit_percentage2:.2f}%&#39;)<br>        arbitrage_found = True<br><br>    # No arbitrage opportunities found<br>    if not arbitrage_found:<br>        print(&#39;No arbitrage found.&#39;)</pre><p>Remark: For a given mat, change in standard currency indicated by i doesn’t matter to the profit percentage result anyway.</p><ol><li>In financial market, assets are typically quoted in two way (bid and ask) for buying and selling. Bid represents the highest price that a buyer is willing to pay for an asset, you will receive the bid price, when you sell an asset; Ask represents the lowest price at which a seller is willing to sell an asset, you will pay the ask price, when you buy an asset. <strong>bid&lt;ask</strong> in general.<br>The difference between bid and ask is the <strong>spread</strong>. This spread serves as a margin for market makers, who are firms or individuals that provide liquidity to the market by continuously quoting both bid and ask prices for assets. They try to maintain a tight spread to stay competitive while profiting from the spread.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e82d063ae4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asked Grok 3: How to verify a stochastic matrix is irreducible?]]></title>
            <link>https://medium.com/@ianchau379/asked-grok-3-how-to-verify-a-stochastic-matrix-is-irreducible-a16f3cded4fc?source=rss-e5c3ec00ad25------2</link>
            <guid isPermaLink="false">https://medium.com/p/a16f3cded4fc</guid>
            <category><![CDATA[stochastic-process]]></category>
            <category><![CDATA[markov-chains]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[linear-algebra]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Ian Chau]]></dc:creator>
            <pubDate>Sun, 23 Feb 2025 15:41:27 GMT</pubDate>
            <atom:updated>2025-02-23T15:41:27.567Z</atom:updated>
            <content:encoded><![CDATA[<h4>Thoughts on state-of-the-art Gen-AI tools as a programmer</h4><p>Recently, I was working on a project that requires a function to receive a stochastic matrix, returning `True` if it is irreducible, `False` otherwise.</p><p><strong>Tldr</strong>: I shared my problem solving journey. I concluded that Gen-AI tools can often provide correct solution to your problem. But also most of the time, the solution does not meet your requirements, that’s why you still need to have a good grasp of the problem and the relevant knowledge in order to communicate your needs and fill in the missing pieces.</p><p>⏭ You can <strong>skip</strong> this part if you are already familiar with stochastic matrices and irreducibility.</p><p>Recall: A <em>stochastic matrix</em> (denote as <em>P</em>) is a square matrix where all entries are non-negative and each row sums are equal to 1. In the context of Markov chains, the entries represent transition probabilities from one state to another.</p><p>A stochastic matrix corresponds to an underlying Markov chain that can be represented as a directed graph. If the probability from state <em>i</em> to state <em>j</em> (denote as <em>P</em>[<em>i,j</em>]) is non-zero, there is a directed edge from node <em>i</em> to node<em> j</em>. The graph is <em>strongly connected</em> if every node can reach every other node, which is equivalent to say the stochastic matrix is <em>irreducible</em>.</p><p>Example: <em>P</em> is reducible because 5 cannot go to 3.</p><figure><img alt="An example of stochastic matrix and the underlying directed graph" src="https://cdn-images-1.medium.com/max/586/0*sIoPHfwlGJ3pcnMm.png" /><figcaption>Photo by <a href="https://math.stackexchange.com/users/134785/user134785">user134785</a> on <a href="https://math.stackexchange.com/">Mathematics Stack Exchange</a></figcaption></figure><p>Before, I asked Gen-AI tools, I already have some idea in my mind. One viable solution is to transform the matrix into a directed graph and then use some sort of algorithm to check its connectivity. Some related algorithms such as Kosaraju’s Algorithm and Tarjan’s Algorithm. See <a href="https://www.geeksforgeeks.org/strongly-connected-components/#efficient-approach-for-finding-strongly-connected-components-sccs">geeksforgeeks</a> for detailed implementations.</p><p>I wouldn’t have to ask Chatgpt if I were to use the solution above. I can directly copy and paste, and then only write a helper function that transforms a given matrix into a directed graph.</p><p>However, I wasn’t tempted to use the solution above (even it is probably the most efficient). Particularly for three reasons:</p><ol><li>I am looking for an easy to understand solution that uses pure linear algebra without having to convert the matrix into a graph.</li><li>I am not sure if such a solution exists at all but I just intuitively think that there is a closed form property for verifying a matrix is reducible, which can then be done in few lines of code.</li><li>The function will mostly receive a matrix with all positive entries that can immediately tell irreducible from its matrix form.</li></ol><p>So I asked gpt-4o “How to verify a stochastic matrix is irreducible?” and below is part of the valuable responses. We can see the solutions look decent, they seem fit to my requirements. However, it’s important to note that a solid understanding of the underlying mathematics is still essential. This ensures that you can select the appropriate algorithm for your needs and confirm that it functions as intended. In my case, I can convince myself the correctness of method 2 and 4, but I need further reading and help to be confident that method 3 is also correct.</p><figure><img alt="Response from gpt-4o" src="https://cdn-images-1.medium.com/max/1024/1*9byULQDM0RG8EMqRwaRLBQ.png" /><figcaption>Response from gpt-4o</figcaption></figure><p>Grok 3 suggested something similar and a Python example that relied on an external library called networkx. But remember, I don’t want a graph solution.</p><pre># Grok 3 DeepSearch suggested Python solution <br>import numpy as np<br>import networkx as nx<br><br>def is_irreducible(P):<br>    &quot;&quot;&quot;<br>    Check if a stochastic matrix is irreducible using networkx.<br>    <br>    Parameters:<br>    P (numpy.ndarray): Stochastic matrix (n x n, non-negative, rows sum to 1)<br>    <br>    Returns:<br>    bool: True if irreducible, False otherwise<br>    &quot;&quot;&quot;<br>    n = P.shape[0]<br>    G = nx.DiGraph()<br>    for i in range(n):<br>        for j in range(n):<br>            if P[i,j] &gt; 0:<br>                G.add_edge(i, j)<br>    return nx.is_strongly_connected(G)<br><br># Example usage<br>P1 = np.array([[0, 1, 0],<br>               [0.5, 0, 0.5],<br>               [0, 1, 0]])<br>print(&quot;Matrix P1 is irreducible:&quot;, is_irreducible(P1))  # True<br><br>P2 = np.array([[1, 0],<br>               [0, 1]])<br>print(&quot;Matrix P2 is irreducible:&quot;, is_irreducible(P2))  # False</pre><p>Great! Both tools give me guide to find my desire solution and at the moment matrix powers method seems the most ideal one. But computing <em>I+P+P²+…+</em>up to power of <em>n</em> requires a for loop. Again, I intuitively think that there is one closed mathematical expression which can evaluate in one line of code. It turns out YES, there is, but I found the solution from online instead of the Gen AI tool giving me the answer directly.</p><p>In the following MATLAB documentation, I found that we can simply compute <em>(I+P)^(n-1) </em>and check that every entries are non-zero to conclude irreducible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mNBZqSDcnBmxYS6OMbxQvw.png" /><figcaption>From MATLAB documentation of <a href="https://www.mathworks.com/help/econ/dtmc.isreducible.html#d126e350201">isreducible(mc)</a></figcaption></figure><p>This is a really strong and surprising result. The proof can be found in the reference material (Page 398–403 of Horn, R., and C. R. Johnson. <em>Matrix Analysis.</em>). But I didn’t really read it seriously because it’s not a simple text and it builds on a lot of prior knowledge. I still write down my thought process at the end of this post to demo the way I understand this theorem quickly. Anyway, we now have the following neat and elegant solution does the same thing to check a stochastic matrix is irreducible or not.</p><pre>import numpy as np<br><br>def is_irreducible(P: numpy.ndarray):<br>    &quot;&quot;&quot;<br>    Check if the stochastic matrix P is irreducible<br>    <br>    Returns:<br>    bool: True if P is irreducible, False otherwise.<br>    &quot;&quot;&quot;<br>    n = P.shape[0]<br>    I = np.eye(n)  # Identity matrix<br><br>    M = I + P<br>    M_power = np.linalg.matrix_power(M, n-1)<br><br>    return np.all(M_power &gt; 0)</pre><p>When I try to ask Grok 3 to validate the correctness of this algorithm with deepsearch capability, unfortunately, it stated that the algorithm is invalid. Grok 3 cannt provide a counterexample as well.</p><figure><img alt="Grok 3 cannt provide a counterexample" src="https://cdn-images-1.medium.com/max/1024/1*RhCPVH8iQ8e8ih0-bX8HVg.png" /><figcaption>Grok 3 cannt provide a counterexample</figcaption></figure><figure><img alt="Grok 3 stated that the algorithm is invalid" src="https://cdn-images-1.medium.com/max/1024/1*I_fuCJDlcu6m2E7eP2yoDg.png" /><figcaption>Grok 3 stated that the algorithm is invalid</figcaption></figure><p>Despite Grok 3’s assertion, I remain confident in the algorithm’s correctness based on mathematical principles. At the same time, I reflected on the role of AI in problem-solving. While AI can provide valuable insights and suggestions, it is the human ability to critically analyze, synthesize information, and understand complex concepts that ultimately drives desire solutions. As we continue to integrate AI into our workflows, we must not let it dictate our work. As in the beginning I could have just accepted the solution AI gave me, but I remain critical to the answers they provided. This approach not only enhances my understanding but also ensures that the solutions I implement are robust and well-founded.</p><p>Starting from Page 398 of <em>Matrix Analysis.</em></p><p>Definition 6.2.7. A strange property of a square matrix called SC is introduced.</p><p>Definition 6.2.10. Let <em>A</em> be any matrix. Then, the operation |<em>A</em>| transforms all elements in <em>A</em> into their absolute values. The indicator matrix <em>M(A)</em> creates a matrix that indicates non-zero elements in <em>A</em> with 1s and zeros with 0s.</p><p>Definition 6.2.11. A square matrix corresponds to an underlying directed graph like our first example.</p><p>Theorem 6.2.14. <em>A</em> has property SC iff the underlying directed graph is strongly connected.</p><p>Comment: Finally, we build a connection between the strange property SC with our familiar property (strongly connected).</p><p>Definition 6.2.21. The concept of a matrix is reducible is introduced. It looks different from the definition we anticipated. But Theorem 6.2.24 tells us they are really just the same things.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3rk63V5gOTRmnBEG3yonA.png" /><figcaption>Extract from page 403 of Horn, R., and C. R. Johnson. <em>Matrix Analysis.</em></figcaption></figure><p>Comment: <em>P</em>=|<em>P</em>|. We have <em>P</em> is irreducible ⟺ <em>(I+P)^(n-1).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a16f3cded4fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Another way to the First Ace Problem]]></title>
            <link>https://medium.com/@ianchau379/another-way-to-the-first-ace-problem-1a2737062383?source=rss-e5c3ec00ad25------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a2737062383</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[brain-teaser]]></category>
            <category><![CDATA[first-post]]></category>
            <category><![CDATA[problem-solving]]></category>
            <dc:creator><![CDATA[Ian Chau]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 14:37:33 GMT</pubDate>
            <atom:updated>2025-02-10T14:40:19.889Z</atom:updated>
            <content:encoded><![CDATA[<p>The <strong>First Ace Problem</strong> is a classic question in probability theory. The problem statement is as follows:</p><p><em>“Shuffle an ordinary deck of 52 playing cards. On the average, how far from the top will the first Ace be?”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cx64fi4z9ZxrrLu_" /><figcaption>Photo by <a href="https://unsplash.com/@mtulard?utm_source=medium&amp;utm_medium=referral">Marin Tulard</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before delving into my solution, I want to walk through some of the clever ways to think about this problem that have been presented on <a href="https://math.stackexchange.com/questions/1138853/expected-number-of-cards-you-should-turn-before-finding-an-ace">Mathematics Stack Exchange</a>.</p><h3>Solution 1.</h3><p>The different methods often arise from considering different ways to shuffle a deck. For example, we can imagine the 48 non-Ace cards evenly distributed in the 5 piles separated by the 4 Aces, so we will need to turn up 48/5+1=10.6 cards to see the first Ace. The solution itself look simple enough. The underlying assumption (evenly distributed) that justifies this solution relies on the <em>Principle of Symmetry.</em></p><h3>Solution 2.</h3><p>Another way is to rely on a combinatorial argument, consider a 52-bit long binary string, where 0 represents a non-Ace cards and 1 represents an Ace. There are 52C4 ways to arrange the 4 0’s and 48 1’s. Alternatively, we can sum up all the cases where the first Ace occurs at a specific position:</p><ul><li>The number of binary string with the first 1 in the 1st position is 51C3.</li><li>The number of binary string with the first 1 in the 2nd position is 50C3.</li><li>dot dot dot</li><li>The number of binary string with the first 1 in the 49th position is 3C3.</li></ul><p>We have 51C3+50C3+· · ·+3C3=52C4. Dividing 52C4 on both sides, we obtain (51C3)/(52C4)+(50C3)/(52C4)+· · ·+(3C3)/(52C4)=1. This equation can be interpreted as a way to express the total probability, where each term corresponds to the probability of the first ace appearing in a specific position. We can apply the definition of expected value to compute the average position of first Ace and we will get the same value of 10.6.</p><h3>My Solution.</h3><p>Imagine we already have a shuffled deck of 48 non-Ace cards, we only need to insert back the 4 Aces randomly, then we will get a shuffled deck. We insert them in order. Insert the first Ace in one of the 49 spaces. After that, our shuffled deck has 49 cards and 3 Aces left. Next, we insert the second Ace in one of the 50 spaces. After that, our shuffled deck has 50 cards and 2 Aces left. Similarly, we insert the remaining Aces to our shuffled deck until there are no more Aces left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7lzStfI4r83j51ZV026AZw.png" /></figure><p>By definition of expected value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9WFWmwXjdkecxAlfgXtWWA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a2737062383" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>