<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Syeda Maham Fahim - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Syeda Maham Fahim - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 05 May 2026 11:02:43 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/syedamahamfahim/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How TCP Turns Round Trip Time and Jitter into Packet Loss ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever noticed that your network connection sometimes feels fast and then suddenly slow, even when nothing obvious has changed? A request that takes 20 ms at one moment can take 80 ms the next, and sometimes it does not return at all. Terms li... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-tcp-turns-round-trip-time-and-jitter-into-packet-loss/</link>
                <guid isPermaLink="false">69837b8b9eb9655b2349db75</guid>
                
                    <category>
                        <![CDATA[ networking ]]>
                    </category>
                
                    <category>
                        <![CDATA[ computer networking ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Packet Loss ]]>
                    </category>
                
                    <category>
                        <![CDATA[ rtt ]]>
                    </category>
                
                    <category>
                        <![CDATA[ jitter ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Syeda Maham Fahim ]]>
                </dc:creator>
                <pubDate>Wed, 04 Feb 2026 17:02:03 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1770224386950/ceeafb62-ae8c-4c70-8239-91ba835b85b7.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever noticed that your network connection sometimes feels fast and then suddenly slow, even when nothing obvious has changed? A request that takes 20 ms at one moment can take 80 ms the next, and sometimes it does not return at all. Terms like RTT, jitter, and packet loss are often used to explain this behavior, but the real connection between them is easy to miss.</p>
<p>In this article, we’ll look at RTT, jitter, and packet loss as parts of a single timing system rather than separate metrics. You’ll start by understanding RTT and why it changes over time. Then you’ll learn how jitter emerges as an extra delay relative to a baseline. Finally, you’ll see how TCP uses this timing information to decide when delay turns into packet loss, with a focus on real protocol behaviour such as TLS and post-quantum TLS handshakes.</p>
<p>The goal is simple: to understand how timing turns into decisions.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-rtt-round-trip-time">RTT (Round Trip Time)</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-baseline-rtt">Baseline RTT</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-baseline-rtt-matters">Why Baseline RTT Matters</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-jitter">What is Jitter?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-jitter-actually-means">What Jitter Actually Means</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-where-jitter-comes-from">Where Jitter Comes From</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-jitter-tells-us">What Jitter Tells Us</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-tcp-learns-rtt-and-jitter">How TCP Learns RTT and Jitter</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-tcp-does-not-know-rtt-in-advance">TCP Does Not Know RTT in Advance</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-srtt-smoothed-rtt">SRTT (Smoothed RTT)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-rttvar-rtt-variance">RTTVAR (RTT Variance)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-tcp-needs-both">Why TCP Needs Both</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-tcp-decides-packet-loss">How TCP Decides Packet Loss</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-tcp-never-sees-a-packet-being-dropped">TCP Never Sees a Packet Being Dropped</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-retransmission-timeout-rto">Retransmission Timeout (RTO)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-delay-vs-packet-loss">Delay vs Packet Loss</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-jitter-turns-into-packet-loss">How Jitter Turns Into Packet Loss</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-rtt-round-trip-time">RTT (Round Trip Time)</h2>
<p>Before talking about delay, jitter, or packet loss, we need to clearly understand what RTT is. If RTT is not clear, everything that comes after it becomes confusing.</p>
<p>RTT stands for <strong>Round Trip Time</strong>. It is the total time taken for a packet to travel from a client to a server and for the response to return to the client.</p>
<p><a target="_blank" href="speedvitals.com"><img src="https://cdn-images-1.medium.com/max/1600/1*tKeOZNVYvkDuXMl4WytN5Q.jpeg" alt="RTT [Image Source: speedvitals.com ]" width="600" height="400" loading="lazy"></a></p>
<p>Assuming you send a packet and receive the reply after 50 milliseconds, then the RTT is 50 ms. That is the basic definition.</p>
<p>But here is the important part: <strong>RTT is not a fixed number.</strong> It changes all the time. Even when you communicate with the same server, RTT can change from one packet to the next. This happens because the network is always changing, and this can be because of any of these reasons:</p>
<ul>
<li><p>Packets waiting in queues</p>
</li>
<li><p>Temporary congestion</p>
</li>
<li><p>Scheduling inside routers</p>
</li>
<li><p>Background traffic on the same path</p>
</li>
</ul>
<p>Let’s assume you connect to Google, and you send a packet now. In practice, RTT can be measured using simple tools. One common way is the <code>ping</code> command, which sends a packet and measures how long it takes for the reply to return.</p>
<pre><code class="lang-python">ping -n <span class="hljs-number">1</span> google.com
</code></pre>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*_cGYjq_VgETjsV6rl6XLZA.png" alt="Ping to google.com showing round-trip time output." width="600" height="400" loading="lazy"></p>
<p>And here, you get the reply after 50 ms.</p>
<pre><code class="lang-python">RTT = <span class="hljs-number">50</span> ms
</code></pre>
<p>That value is real, but it is incomplete. A single RTT measurement does not tell us whether the network path itself takes 50 ms, or whether the path is faster and the packet experienced a small temporary delay along the way.</p>
<p>For example, the actual path delay might be 49 ms, with an additional 1 ms spent waiting in a queue. From a single RTT value, there is no way to separate these effects. RTT only makes sense after multiple measurements.</p>
<p>So, let’s measure multiple RTT values.</p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*ecgJnU89HtE9FVzczJue4g.png" alt="Ping to google.com showing multiply round-trip time output." width="600" height="400" loading="lazy"></p>
<p>Now you can see a pattern. From the measurements:</p>
<pre><code class="lang-python">min RTT ≈ <span class="hljs-number">18</span> ms
max RTT ≈ <span class="hljs-number">19</span> ms
average RTT ≈ <span class="hljs-number">18</span> ms
</code></pre>
<p>That is why RTT is not something you magically know from one packet. It is something you observe over time.</p>
<p>But now, at this point, an important question comes up: <strong>Which of these RTT values represents the real network path?</strong></p>
<p>When RTT is measured repeatedly, the values are not consistent. Some RTT measurements are small, some are larger, and some suddenly jump due to temporary network conditions.</p>
<p>You may see something like this: <code>small, small, small, small, BIG</code>. That is why we need a reference point, which we can call the stable point. Without it, every RTT value looks equally confusing, and we cannot tell whether a packet was slow because the path itself is slow or because something temporary happened.</p>
<h3 id="heading-baseline-rtt">Baseline RTT</h3>
<p>That stable point is the baseline RTT. Baseline RTT means the <strong>minimum RTT observed over time</strong>. This represents the RTT without temporary effects.</p>
<p>For example, in the above example, our repeated measurements show minimum RTT ≈ 18 ms. 18 ms becomes our baseline RTT. You can think of baseline RTT as the fastest possible RTT for a given path, representing the calm state of the network where packets do not wait in queues, there is no congestion, and no retransmissions occur.</p>
<p>In other words, baseline RTT reflects what the network is capable of when nothing unusual is happening. The best happy case that usually excludes temporary effects.</p>
<h3 id="heading-why-baseline-rtt-matters"><strong>Why Baseline RTT Matters</strong></h3>
<p>Once we have a baseline RTT, individual RTT measurements stop feeling random. We can see when an RTT is close to the baseline, when it is higher than expected, and when extra delay has been introduced by temporary network conditions.</p>
<p>Without a baseline RTT, each RTT value stands alone, and comparison becomes guesswork. With a baseline in place, RTT values gain meaning, variation becomes visible, and we are finally able to reason about what causes RTT to increase, which naturally leads to jitter.</p>
<p>This is the point where we are finally ready to talk about <strong>what causes RTT to increase</strong>, which leads naturally to jitter.</p>
<h2 id="heading-what-is-jitter">What is Jitter?</h2>
<p>Now comes Jitter. Once we have a baseline RTT, something important becomes clear. Most RTT values are not equal to the baseline. They are usually higher.</p>
<p>So the next natural question is: <strong>If baseline RTT shows the calm network, what is causing the RTT to increase in the other measurements?</strong></p>
<p>That extra part is what we call jitter.</p>
<h3 id="heading-what-jitter-actually-means">What Jitter Actually Means</h3>
<p>Jitter is the extra delay added on top of the baseline RTT. In simple words, baseline RTT shows what the network can do when nothing is wrong, while jitter describes what happens when the network becomes busy, and packets experience extra delay.</p>
<p>So every observed RTT can be thought of like this: <code>Observed RTT = Baseline RTT + Extra Delay</code></p>
<p><strong><em>Example</em></strong></p>
<p><img src="https://cdn-images-1.medium.com/max/1600/1*T6bC3VvXULV5CIVRixg-uA.png" alt="Observed RTT and Jitter." class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>Baseline RTT = 18 ms. That extra delay is jitter.</p>
<p>There are two important points to remember. First, jitter is always positive because a packet can be delayed but can never arrive faster than the baseline RTT. Second, baseline RTT acts as the reference point, which means jitter only exists relative to that baseline. Without a baseline, jitter has no meaning.</p>
<h3 id="heading-where-jitter-comes-from">Where Jitter Comes From</h3>
<p>Jitter appears when packets do not move immediately through the network.</p>
<p>This usually happens because of:</p>
<ul>
<li><p>Packets waiting in queues</p>
</li>
<li><p>Routers delaying packets before forwarding</p>
</li>
<li><p>Temporary congestion on links</p>
</li>
<li><p>Retransmissions after drops</p>
</li>
</ul>
<p>These effects are not constant. They come and go. Because of that, jitter is irregular and bursty. Sometimes it is very small, and at other times it can suddenly become large.</p>
<h3 id="heading-what-jitter-tells-us">What Jitter Tells Us</h3>
<p>At this stage, jitter is still just an observation. It tells us how unstable the network timing is and how often packets experience extra delay. We are not making decisions yet. We are only describing what the network is doing.</p>
<h2 id="heading-how-tcp-learns-rtt-and-jitter">How TCP Learns RTT and Jitter</h2>
<p>We have seen that:</p>
<ul>
<li><p>RTT changes over time</p>
</li>
<li><p>Baseline RTT gives us a reference</p>
</li>
<li><p>Jitter explains extra delay</p>
</li>
</ul>
<p>So, up to this point, we have only been observing the network. But now a new question appears: If RTT keeps changing, and if delay and jitter exist, <strong>who is actually watching all this?</strong> More importantly, <strong>who decides when waiting is normal and when waiting becomes a problem?</strong></p>
<p>This is the point where <strong>TCP</strong> enters the picture. TCP is the component that observes these timing changes and uses them to decide what to do next.</p>
<h3 id="heading-tcp-does-not-know-rtt-in-advance">TCP Does Not Know RTT in Advance</h3>
<p>TCP does not start with any knowledge of how long the path is, how stable the network will be, or how much delay to expect. It learns all of this dynamically while the connection is running.</p>
<p>TCP learns everything <strong>while the connection is running</strong>, only by looking at time. Every time TCP sends data and receives an acknowledgement, it gets one RTT sample. Over time, these samples are used to build expectations.</p>
<p>To make sense of these timing samples, TCP maintains two internal values that summarize what it has learned so far.</p>
<h3 id="heading-srtt-smoothed-rtt">SRTT (Smoothed RTT)</h3>
<p>SRTT is the RTT that TCP expects most of the time. It is not the minimum RTT, and it is not a simple average. It is a smoothed value that represents the normal RTT that the TCP has learned from recent history. This means recent RTT measurements matter more, while older RTT measurements gradually matter less.</p>
<p>Because of this, SRTT does not jump because of a single delayed packet. Instead, it adapts gradually as network conditions change.</p>
<p>For example, suppose TCP observes these RTT samples (in ms): 48, 50, 49, 51, 50.</p>
<p>Then TCP smooths these values into a stable expectation, such as: SRTT ≈ 50 ms.</p>
<p>You can think of SRTT as: The RTT that TCP believes is reasonable for this connection, based mostly on recent history. It is a memory-weighted average, biased toward recent RTT values.</p>
<h3 id="heading-rttvar-rtt-variance">RTTVAR (RTT Variance)</h3>
<p>RTTVAR tells TCP <strong>how much RTT is changing</strong>. Now compare two situations.</p>
<p><strong>Stable RTT</strong></p>
<p>RTT samples: <code>49, 50, 51, 50</code></p>
<p>Because these values are close to each other, the variation is small, RTTVAR remains low, and TCP feels confident about its timing estimates.</p>
<p><strong>Unstable RTT</strong></p>
<p>RTT samples: <code>50, 52, 90, 48</code></p>
<p>Here, the sudden jump increases variation, causes RTTVAR to rise, and makes TCP less confident about its timing.</p>
<h3 id="heading-why-tcp-needs-both">Why TCP Needs Both</h3>
<p>SRTT alone is not enough for TCP to make reliable timing decisions. If TCP only knew that the RTT is around 50 ms, it would still have no way to tell whether delays are stable or whether sudden spikes are common.</p>
<p>RTTVAR fills this gap by capturing how much RTT changes over time. While SRTT tells TCP what RTT to expect under normal conditions, RTTVAR tells TCP how confident it should be in that expectation.</p>
<p>At this stage, TCP is still <strong>learning</strong>, not judging. It is building a timing model of the network.</p>
<p>So far, the network produces RTT variation, baseline RTT provides a calm reference, jitter explains extra delay, and TCP observes all of this using SRTT and RTTVAR.</p>
<p>TCP now has expectations. Only after this point does TCP start making decisions. And one of those decisions is packet loss.</p>
<h2 id="heading-how-tcp-decides-packet-loss">How TCP Decides Packet Loss</h2>
<p>Now that TCP has learned what RTT usually looks like and how much it varies, it has to answer one important question: <strong>How long should I wait before assuming a packet is gone?</strong></p>
<p>This is where packet loss comes in.</p>
<h3 id="heading-tcp-never-sees-a-packet-being-dropped">TCP Never Sees a Packet Being Dropped</h3>
<p>TCP does not see routers, queues, or links, and it does not know where packets go. TCP only sees time. It sends data and then waits.</p>
<p>If the acknowledgment arrives in time, everything is fine. If it does not, TCP must decide what to do next.</p>
<h3 id="heading-retransmission-timeout-rto">Retransmission Timeout (RTO)</h3>
<p>To make this decision, TCP uses the Retransmission Timeout, or RTO. RTO is not random. It is computed from what TCP has already learned about network timing.</p>
<p>Conceptually, RTO is calculated as:</p>
<pre><code class="lang-markdown">RTO=SRTT+max(𝐺,4×RTTVAR)
</code></pre>
<p>Here, SRTT sets the expected delay, while RTTVAR adds extra margin to account for jitter. As a result, RTO represents how long TCP is willing to wait, based on how uncertain the network timing is.</p>
<p>Suppose TCP has learned that the SRTT is 50 ms and the RTTVAR is 5 ms. In that case, the RTO becomes 70 ms.</p>
<p>RTO = 50 + 4 × 5<br>RTO = 70 ms</p>
<p>Now TCP behavior is simple:</p>
<ul>
<li><p>ACK arrives at <strong>60 ms</strong> → delay</p>
</li>
<li><p>ACK arrives at <strong>75 ms</strong> → packet loss</p>
</li>
</ul>
<p>The network is the same, and the packet is the same. Only the arrival time changes, and that alone leads to a different decision.</p>
<h3 id="heading-delay-vs-packet-loss">Delay vs Packet Loss</h3>
<p>TCP logic is simple. If a packet arrives before the RTO expires, it is treated as delay. If it does not arrive before the RTO, TCP declares it lost.</p>
<p>This leads to an important rule: <strong>packet loss is a timing decision, not a certainty</strong>. The packet may still arrive later, but once the RTO expires, TCP has already acted.</p>
<h3 id="heading-how-jitter-turns-into-packet-loss">How Jitter Turns Into Packet Loss</h3>
<p>This behaviour connects directly to jitter. As long as jitter stays within the RTO window, packets are delayed but not considered lost. When jitter becomes large enough that delays cross the RTO boundary, TCP interprets delay as packet loss.</p>
<p>So packet loss does not always mean a packet disappeared. Often, it means the network timing has become too unpredictable.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>At this point, everything connects: RTT, jitter, and packet loss are not separate network metrics. They describe different parts of the same timing process.</p>
<ul>
<li><p>RTT shows how long communication usually takes.</p>
</li>
<li><p>Baseline RTT gives a stable reference.</p>
</li>
<li><p>Jitter explains why delays change.</p>
</li>
<li><p>Packet loss appears when that variation exceeds what the protocol can tolerate.</p>
</li>
</ul>
<p>Once this flow is clear, network behavior stops feeling random. It becomes a matter of timing, uncertainty, and decisions.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Are Logs in Programming? ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever run a program, and it crashed? No error messages, no hints, just silence. How do you figure out what went wrong? That's where logging saves the day. Logs keep track of what’s happening inside your code so that when things go wrong, you ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-logs-in-programming/</link>
                <guid isPermaLink="false">67abe1c4e2819029e77c7459</guid>
                
                    <category>
                        <![CDATA[ logging ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Syeda Maham Fahim ]]>
                </dc:creator>
                <pubDate>Tue, 11 Feb 2025 23:48:20 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738685115991/600c01b6-b031-4ce9-a77a-5d88fcdaa68a.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever run a program, and it crashed? No error messages, no hints, just silence. How do you figure out what went wrong? That's where logging saves the day.</p>
<p>Logs keep track of what’s happening inside your code so that when things go wrong, you don’t have to guess. They’re similar to <code>print</code> or <code>console.log</code>, but more powerful.</p>
<p>In this tutorial, I will use Python to create and walk you through some logging code examples.</p>
<p>Before we talk about logs, let’s understand the different error types you might use or encounter.</p>
<h2 id="heading-types-of-errors">Types of Errors</h2>
<p>When you’re building a production-level application, you need to display errors based on their severity. There are several error types, and the most important ones are:</p>
<ul>
<li><p><strong>DEBUG:</strong> Detailed information, typically useful for diagnosing problems.</p>
</li>
<li><p><strong>INFO:</strong> General information about the program’s progress.</p>
</li>
<li><p><strong>WARNING:</strong> Something unexpected happened, but it’s not critical.</p>
</li>
<li><p><strong>ERROR:</strong> An error occurred, but the program can still run.</p>
</li>
<li><p><strong>CRITICAL:</strong> A very serious error that may stop the program from running.</p>
</li>
</ul>
<h2 id="heading-what-is-logging">What is Logging?</h2>
<p>Now, let’s get straight to the point and understand what logging is.</p>
<p>In simple terms, logs or logging is the act of recording information about everything your program does. The recorded information could be anything, from basic details like which functions were called to more detailed ones like tracking errors or performance issues.</p>
<h3 id="heading-why-do-we-need-logging">Why Do We Need Logging?</h3>
<p>You might be thinking, "If logs are printing errors, info, and so on, I can just use print statements. Why do I need logging?" Well, <code>print</code> works, but logging gives you more control:</p>
<p>↳ It can store messages in a file.<br>↳ It has different levels (info, warning, error, and so on).<br>↳ You can filter messages based on importance.<br>↳ It helps in debugging without cluttering your code.</p>
<p>These are things <code>print</code> statements can't do effectively.</p>
<h2 id="heading-how-to-add-logs-in-python">How to Add Logs in Python</h2>
<p>In Python, the <code>logging</code> module is built specifically for logging purposes.</p>
<p>Let’s set up some logs to see how they work.</p>
<h3 id="heading-step-1-import-the-logging-module">Step 1: Import the Logging Module</h3>
<p>To start using logging, we need to import the module:</p>
<pre><code class="lang-bash">import logging
</code></pre>
<h3 id="heading-step-2-log-messages">Step 2: Log Messages</h3>
<p>Now, you can start logging messages in your program. You can use different log levels based on the importance of the message. As a reminder, those levels are (from least to most urgent):</p>
<ul>
<li><p>DEBUG</p>
</li>
<li><p>INFO</p>
</li>
<li><p>WARNING</p>
</li>
<li><p>ERROR</p>
</li>
<li><p>CRITICAL</p>
</li>
</ul>
<p>Let’s log a simple message at each level:</p>
<pre><code class="lang-bash">logging.debug(<span class="hljs-string">"This is a debug message"</span>)
logging.info(<span class="hljs-string">"This is an info message"</span>)
logging.warning(<span class="hljs-string">"This is a warning message"</span>)
logging.error(<span class="hljs-string">"This is an error message"</span>)
logging.critical(<span class="hljs-string">"This is a critical message"</span>)
</code></pre>
<p>When you run this, you’ll see a message printed to the console, similar to this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738500126070/a2a395c3-5cbe-4f94-bea2-d871cfc1529e.png" alt="Terminal showing Python log messages." class="image--center mx-auto" width="579" height="192" loading="lazy"></p>
<p>You might wonder why you don’t see the <strong>DEBUG</strong> and <strong>INFO</strong> messages. The default logging level prevents this.</p>
<p>By default, the logging level is set to <code>WARNING</code>. This means that only messages with a severity of <code>WARNING</code> or higher will be displayed (that is, <code>WARNING</code>, <code>ERROR</code>, and <code>CRITICAL</code>).</p>
<h3 id="heading-step-3-set-up-the-basic-configuration"><strong>Step 3:</strong> Set Up the Basic Configuration</h3>
<p>To see the <code>debug</code> and <code>info</code> messages, we need to set the logging level <code>DEBUG</code> before running the code.</p>
<p>This means we need to configure the logs. So to do this, use the method <code>basicConfig</code> below:</p>
<pre><code class="lang-bash">logging.basicConfig(level=logging.DEBUG)
</code></pre>
<p>This basic configuration allows you to log messages at the <strong>DEBUG</strong> level or higher. You can change the level depending on the type of logs you want.</p>
<p>Now, all logs are printing:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738500423798/96b65689-f0e4-4663-9d1a-1dc7147e964e.png" alt="log messages: debug, info, warning, error, critical." class="image--center mx-auto" width="479" height="125" loading="lazy"></p>
<h3 id="heading-step-4-log-to-a-file">Step 4: Log to a File</h3>
<p>Now, let’s save these logs in a file so we can keep track of errors, as well as when they occurred. To do this, update the configuration:</p>
<pre><code class="lang-bash">logging.basicConfig(filename=<span class="hljs-string">'data_log.log'</span>, level=logging.DEBUG, 
                    format=<span class="hljs-string">'%(asctime)s - %(levelname)s - %(message)s'</span>)
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>asctime</code> – The time when the event occurred.</p>
</li>
<li><p><code>levelname</code> – The type of the log (for example, <strong>DEBUG</strong>, <strong>INFO</strong>).</p>
</li>
<li><p><code>message</code> – The message we display.</p>
</li>
</ul>
<p>Now, when you run the program, the log file will generate and save your logs, showing the exact timing, error type, and message. Like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738500713832/7895f1db-8740-494a-86dd-86020f4f5569.png" alt="Log file with debug, info, warning, error, critical messages" class="image--center mx-auto" width="1182" height="753" loading="lazy"></p>
<h2 id="heading-how-to-use-loggers-for-more-control">How to Use Loggers for More Control</h2>
<p>If you’re working on a large project, you might want a utility logger that you can use anywhere in the code. Let’s create this custom logger.</p>
<p>First, we’ll update the <code>basicConfig</code> to add the filename, line number, and ensure it writes everything, even special characters:</p>
<pre><code class="lang-bash">logging.basicConfig(
        filename=log_file,
        level=logging.DEBUG,
        format=<span class="hljs-string">'%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'</span>, 
        filemode=<span class="hljs-string">'w'</span>,
        encoding=<span class="hljs-string">'utf-8'</span> 
    )
</code></pre>
<p>Explanation:</p>
<ul>
<li><p><code>encoding='utf-8'</code> — Ensures special characters are logged.</p>
</li>
<li><p><code>%(filename)s:%(lineno)d</code> — Logs the filename and line number where the log was generated.</p>
</li>
</ul>
<p>Now, let’s set up a custom console logger:</p>
<pre><code class="lang-bash">  console_handler = logging.StreamHandler()
  console_handler.setLevel(logging.DEBUG)
  console_formatter = logging.Formatter(<span class="hljs-string">'%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'</span>)  <span class="hljs-comment"># Added line number</span>
  console_handler.setFormatter(console_formatter)


   logging.getLogger().addHandler(console_handler)
</code></pre>
<p>This setup does the following:</p>
<ul>
<li><p><code>console_handler</code>: Sends log messages to the console (stdout).</p>
</li>
<li><p><code>console_formatter</code>: Formats the log message with time, level, filename, line number, and the message.</p>
</li>
<li><p><code>logging.getLogger().addHandler(console_handler)</code>: Adds the custom handler to the root logger, so the log messages are printed to the console.</p>
</li>
</ul>
<h3 id="heading-full-example-code">Full Example Code</h3>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> logging
<span class="hljs-keyword">import</span> os
<span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">setup_daily_logger</span>():</span>
    base_dir = os.path.dirname(os.path.abspath(__file__))
    log_dir = os.path.join(base_dir, <span class="hljs-string">'logs'</span>)  
    os.makedirs(log_dir, exist_ok=<span class="hljs-literal">True</span>)


    current_time = datetime.now().strftime(<span class="hljs-string">"%m_%d_%y_%I_%M_%p"</span>)
    log_file = os.path.join(log_dir, <span class="hljs-string">f"<span class="hljs-subst">{current_time}</span>.log"</span>)


    logging.basicConfig(
        filename=log_file,
        level=logging.DEBUG,
        format=<span class="hljs-string">'%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'</span>, 
        filemode=<span class="hljs-string">'w'</span>,
        encoding=<span class="hljs-string">'utf-8'</span> 
    )


    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)
    console_formatter = logging.Formatter(<span class="hljs-string">'%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'</span>)  <span class="hljs-comment"># Added line number</span>
    console_handler.setFormatter(console_formatter)


    logging.getLogger().addHandler(console_handler)


    <span class="hljs-keyword">return</span> logging.getLogger(__name__)
</code></pre>
<h3 id="heading-what-happens-now">What Happens Now?</h3>
<p>Now, whenever you run the program, a new log file will be created in the <code>logs</code> folder. Each time the program is executed, a new log file with a unique timestamp will be generated.</p>
<p>Like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738503550743/1ad9fb99-762a-4ca9-a189-58d044955617.png" alt="custom log used in app.py" class="image--center mx-auto" width="1243" height="470" loading="lazy"></p>
<p>These logs will give you a clear picture of your program’s behavior and help with debugging.</p>
<p>I hope this article helped you get a clearer picture of logs and their importance in programming.</p>
<h1 id="heading-practical-real-world-examples">Practical Real-World Examples</h1>
<p>Now that you understand what logs are and how to set them up in Python, let’s look at real-world use cases.</p>
<h2 id="heading-1-bot-scraping-koreas-largest-property-website">1. Bot: Scraping Korea’s Largest Property Website</h2>
<p>Here’s an example of a bot designed to scrape Korea’s biggest property website.</p>
<ul>
<li><p>The logs show every step the bot takes, making it easier to track progress.</p>
</li>
<li><p>If an error occurs at any step, it gets recorded in the log file.</p>
</li>
<li><p>Even if the bot crashes, I can check the logs to pinpoint where things went wrong.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739037891010/69a8b5ae-d202-4466-add0-bb2ace28230a.png" alt="Log file with INFO messages showing city and town extraction details." class="image--center mx-auto" width="1331" height="926" loading="lazy"></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739037833210/bf9ceba0-2caf-48c6-bdb8-ac2d9eb901bd.png" alt="Log file with INFO messages showing city and town extraction details." class="image--center mx-auto" width="1685" height="961" loading="lazy"></p>
<p>One of the methods in this bot’s class uses logging to track whether the bot correctly selects the province.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739038058017/6153c909-477d-4cd6-b493-124b96bc595f.png" alt="select_province function that utilizes logging" class="image--center mx-auto" width="2528" height="1436" loading="lazy"></p>
<p>Here:</p>
<ul>
<li><p>If an error or warning occurs, it’s saved in the log file.</p>
</li>
<li><p>Later, you can review the logs and find out exactly what happened</p>
</li>
</ul>
<h2 id="heading-2-bot-scraping-facebook-groups">2. Bot: Scraping Facebook Groups</h2>
<p>Now, let’s see how logging helps in a Facebook group scraper.</p>
<h5 id="heading-error-tracking">Error Tracking</h5>
<ul>
<li><p>At one point, the bot failed due to an error.</p>
</li>
<li><p>Since we had logging in place, the error was saved in the log file.</p>
</li>
<li><p>This allows you to quickly find out what went wrong.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739038507530/9662bed7-a124-4dd8-94a9-9d657ec022a1.png" alt="Error log file" class="image--center mx-auto" width="1849" height="641" loading="lazy"></p>
<p>Here, you see the exact filename and line number where the error occurs.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1739038826232/ce717b49-e532-4c5f-a40d-955591aa27a2.png" alt="Logs file shows success logs" class="image--center mx-auto" width="1861" height="996" loading="lazy"></p>
<p>Once we identified and fixed the issue, the bot started working again.</p>
<p>It captures every detail in the log, saving hours of debugging by pinpointing where errors occur.</p>
<h5 id="heading-debugging-made-easy">Debugging Made Easy</h5>
<ul>
<li><p>The logs recorded every detail of the bot’s execution.</p>
</li>
<li><p>This can save you hours of debugging because you’ll know exactly where the error occurred.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Logging is one of those things no one thinks about until something breaks. But when it does, logs become your best friend.</p>
<p>Remember:</p>
<ul>
<li><p>Logging isn’t just for error tracking—it helps you monitor your program’s flow.</p>
</li>
<li><p>Instead of guessing what went wrong, check the logs. The answer is usually right there.</p>
</li>
</ul>
<p>Make sure to add logging to your code. You’ll thank yourself later!</p>
<p><strong>Stay Connected - @syedamahamfahim 🐬</strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is a Process ID? How to Use PIDs for Process Management ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever wondered how a computer knows which program’s output to display, especially when multiple programs are running simultaneously? This is possible because of the Process ID (PID). A PID is a unique identifier that helps the operating syste... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-a-process-id-process-management-tutorial/</link>
                <guid isPermaLink="false">679bb8262a7ebc3c99ecb6ea</guid>
                
                    <category>
                        <![CDATA[ System administration ]]>
                    </category>
                
                    <category>
                        <![CDATA[ cmd ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Syeda Maham Fahim ]]>
                </dc:creator>
                <pubDate>Thu, 30 Jan 2025 17:34:30 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738252940529/8ee6969c-7a74-4b2f-bd33-f2d48332e8e0.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever wondered how a computer knows which program’s output to display, especially when multiple programs are running simultaneously? This is possible because of the Process ID (PID).</p>
<p>A PID is a unique identifier that helps the operating system track and manage running programs.</p>
<p>In this article, we’ll explore what a Process ID (PID) is, why it’s important, and how you can use it to manage processes, including terminating a program when necessary.</p>
<h2 id="heading-understanding-pids-how-does-a-computer-identify-running-programs">Understanding PIDs: How Does a Computer Identify Running Programs?</h2>
<p>Let’s consider two Python scripts:</p>
<ul>
<li><p><code>hello_maham.py</code> → <code>print("Hello Maham")</code></p>
</li>
<li><p><code>hello_amna.py</code> → <code>print("Hello Amna")</code></p>
</li>
</ul>
<p>How does the computer know that <code>hello_maham.py</code> should show the output "Hello Maham" and not "Hello Amna" from <code>hello_amna.py</code>?</p>
<p>If you think it just happens magically, then think again! This happens because of something called a <strong>Process ID (PID)</strong>.</p>
<p>In any operating system, processes are constantly running in the background to execute tasks. Whether it’s a program you launched manually or a system task running automatically, each of these processes is assigned a unique PID.</p>
<p>Let’s break this down further.</p>
<h2 id="heading-what-is-a-process-id-pid">What is a Process ID (PID)?</h2>
<p>Simply put,</p>
<blockquote>
<p><em>A</em> <strong><em>Process ID (PID)</em></strong> <em>is a unique identifier assigned to each process running in an operating system.</em></p>
</blockquote>
<p>Let’s understand what’s going on in the background.</p>
<p>Whenever a program runs, no matter the language, it needs memory and time to execute. So, when you run a program, the operating system creates a new process for it. To identify the program, the computer assigns it a unique identifier – the <strong>Process ID</strong> – and then it begins execution.</p>
<p>Let’s revisit our previous example:</p>
<ul>
<li><p>When you run <code>hello_maham.py</code>, the system assigns a unique PID to it.</p>
</li>
<li><p>Similarly, when you run <code>hello_amna.py</code>, it gets its own unique PID.</p>
</li>
</ul>
<p>This is why the outputs of both scripts don’t overlap!</p>
<p>Now, you got it? Each time a new process is created, the system ensures that every process gets a different PID. This PID is used by the system to manage and interact with processes. Its called <strong>Uniqueness Of PIDs</strong></p>
<h3 id="heading-how-does-the-computer-handle-this-id">How Does the Computer Handle This ID?</h3>
<p>Now you may wonder, does the computer have millions of PIDs? After all, we could be running many programs at once.</p>
<p>The answer is <strong>no</strong>. Once a process ends, the PID becomes available again for reuse. This means that PIDs are reusable, and there is no shortage of them.</p>
<h3 id="heading-but-why-and-when-do-i-need-pids">But Why and When Do I Need PIDs?</h3>
<p>Now that you know what a PID is, you might be wondering: <strong>Why do I need this?</strong></p>
<p>Well, PIDs are actually very useful for system administrators and developers. They help in:</p>
<p><strong>System admins and developers manage processes</strong>. Like, if something’s not working properly, you need to be able to find and stop the specific process causing the issue, right?</p>
<p>PIDs are also important for <strong>resource management<em>.</em></strong> The operating system uses them to allocate memory and CPU time to each process, so no one program hogs everything.</p>
<h2 id="heading-how-to-find-the-pid-of-a-running-program">How to Find the PID of a Running Program</h2>
<p>Up until now, we've covered the theoretical concepts. Now, you might be wondering: How do I actually find the PID of a program on my computer?</p>
<p>Well, here are some simple ways to find the <strong>PID</strong> of a running program using various commands in the terminal.</p>
<p>Note, that I’ve used Bash to execute the PID command and included a screenshot for it. But for other terminals like CMD and PowerShell, the respective commands are mentioned at the end.</p>
<p>Some of these methods include:</p>
<h3 id="heading-1-using-the-ps-command">1. Using the <code>ps</code> Command</h3>
<p>The <code>ps</code> command shows a snapshot of the current running processes and their PIDs.</p>
<pre><code class="lang-bash">ps aux | grep &lt;program_name&gt;
</code></pre>
<p>Here’s an example:</p>
<pre><code class="lang-bash">ps aux | grep python
</code></pre>
<p>This command will display all the Python processes running on the system, along with their PIDs.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737914130884/686568b8-77d5-439d-a08b-61e18d4e5d56.png" alt="Python processes running plus their PIDs" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h3 id="heading-2-using-the-top-command">2. Using the <code>top</code> Command</h3>
<p>The <code>top</code> command shows real-time information about processes running on the system, including their PIDs.</p>
<pre><code class="lang-bash">top
</code></pre>
<p>Look under the <strong>PID</strong> column to find the process you're interested in.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1737914189672/43f93890-2e06-42a8-b61b-9103227cf912.png" alt="Result of running the top command" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-kill-a-process-using-its-pid">How to Kill a Process Using its PID</h2>
<p>What if you want to <strong>kill</strong> the program? Whether it’s a cron job or a program that is misbehaving or running for too long, how can you stop it using the PID?</p>
<p>Let’s go through how you can do that:</p>
<h3 id="heading-1-using-the-kill-command">1. Using the <code>kill</code> Command</h3>
<p>To terminate a process, use the <code>kill</code> command followed by the PID:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">kill</span> &lt;PID&gt;
</code></pre>
<p>Here’s an example:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">kill</span> 1234
</code></pre>
<p>This command will gracefully terminate the process with PID <code>1234</code>.</p>
<h3 id="heading-2-using-the-kill-9-command-force-kill">2. Using the <code>kill -9</code> Command (Force Kill)</h3>
<p>If the process does not stop after using the regular <code>kill</code> command, you can force kill it using the <code>kill -9</code> command:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">kill</span> -9 &lt;PID&gt;
</code></pre>
<p>Here’s an example:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">kill</span> -9 1234
</code></pre>
<p>This forcefully terminates the process and bypasses any shutdown procedures it may have, so make sure you use it with caution.</p>
<h2 id="heading-how-to-stop-cron-jobs-using-a-pid-practical-example">How to Stop Cron Jobs Using a PID – Practical Example</h2>
<p>So, let’s say you’ve got a cron job running, and it’s acting up. How do you stop it?</p>
<p>Cron jobs are scheduled tasks that run automatically at specific intervals.</p>
<p>If you need to stop a running cron job, you can use the PID of the process running the cron job.</p>
<h3 id="heading-stop-a-running-cron-job">Stop a Running Cron Job</h3>
<p>If you need to stop a running cron job, you can use the PID of the process running the cron job.</p>
<p>Here’s how to kill a cron job:</p>
<ol>
<li><p><strong>Find the PID</strong>: Use the <code>ps</code> or <code>pgrep</code> command to find the PID of the cron job. Example:</p>
<pre><code class="lang-bash"> ps aux | grep cron
</code></pre>
</li>
<li><p><strong>Kill the Cron Job</strong>: Once you find the PID of the cron job, use the <code>kill</code> or <code>kill -9</code> command to stop it.</p>
</li>
</ol>
<h2 id="heading-commands-for-other-terminals">Commands For Other Terminals:</h2>
<p>Here’s how to manage processes in different terminals:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Action</td><td>CMD Command</td><td>PowerShell Command</td><td>Bash Command</td></tr>
</thead>
<tbody>
<tr>
<td><strong>List all processes</strong></td><td><code>tasklist</code></td><td><code>Get-Process</code></td><td><code>ps aux</code></td></tr>
<tr>
<td><strong>Find process by name</strong></td><td><code>tasklist</code></td><td><code>findstr &lt;name&gt;</code></td><td><code>Get-Process</code></td></tr>
<tr>
<td><strong>Kill process by PID</strong></td><td><code>taskkill /PID &lt;PID&gt;</code></td><td><code>Stop-Process -Id &lt;PID&gt;</code></td><td><code>kill &lt;PID&gt;</code></td></tr>
<tr>
<td><strong>Force kill process</strong></td><td><code>taskkill /F /PID &lt;PID&gt;</code></td><td><code>Stop-Process -Id &lt;PID&gt; -Force</code></td><td><code>kill -9 &lt;PID&gt;</code></td></tr>
</tbody>
</table>
</div><h2 id="heading-conclusion">Conclusion</h2>
<p>Understanding <strong>Process IDs</strong> is key to managing processes on your computer. With simple commands, you can easily find and stop problematic processes, ensuring smooth system operation.</p>
<p>So, stay in control of your system with PIDs!</p>
<p><strong>Stay connected — @syedamahamfahim 🐬</strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is a Floating-Point Arithmetic Problem? ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever worked with numbers like 1/3, where the result is 0.33333… and continues forever? As humans, we naturally round off such numbers, but have you ever wondered how computers handle them? In this article, you’ll explore how computers manage... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-a-floating-point-arithmetic-problem/</link>
                <guid isPermaLink="false">671a576a1d53cf0b6813a51c</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Maths ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Mathematics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ float ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Syeda Maham Fahim ]]>
                </dc:creator>
                <pubDate>Thu, 24 Oct 2024 14:19:22 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1729588035734/9824633d-727a-49ce-9080-0fa3a7b18ed6.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever worked with numbers like 1/3, where the result is 0.33333… and continues forever? As humans, we naturally round off such numbers, but have you ever wondered how computers handle them?</p>
<p>In this article, you’ll explore how computers manage continuous values, including the concept of precision errors. We’ll examine the floating-point arithmetic problem, a universal issue that affects many programming languages. We’ll focus specifically on how JavaScript addresses this challenge.</p>
<p>Additionally, you’ll learn how binary operations work behind the scenes, the threshold at which JavaScript truncates numbers based on the IEEE 754 standard, and introduce <code>BigInt</code> as a solution for accurately handling larger numbers without precision loss.</p>
<p>First, let's consider an example. Can you guess the output of this operation?</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">0.1</span> + <span class="hljs-number">0.2</span>);
</code></pre>
<p>You may think the answer is 0.3, right? But no, the actual output is:</p>
<pre><code class="lang-javascript">Output: <span class="hljs-number">0.30000000000000004</span>
</code></pre>
<p>You must be wondering why this is happening. Why so many extra zeros, and why does it end with a 4?</p>
<p>The answer is simple: the numbers 0.1 and 0.2 cannot be precisely represented in JavaScript (that is, "exactly" or "accurately.")</p>
<p>It sounds simple, right? But the explanation is a bit more complex.</p>
<p>So, what do you think—bug or feature?</p>
<p>Well, it’s not a bug. It’s actually a fundamental issue with how computers handle numbers, specifically floating-point numbers.</p>
<h2 id="heading-why-does-this-happen">Why Does This Happen?</h2>
<p>Let’s understand this with basic math.</p>
<p>The fraction 1/3 is represented in decimal by 0.33333... and it never ends. This means that 3 repeats itself infinitely. We can’t write it down exactly, so we approximate it to something like 0.333 or 0.333333 to save time and space.</p>
<p>Similarly, in a computer, we also have to approximate because 1/3 or 0.3333... would be a very large number and take up infinite space (which we don’t have).</p>
<p>This leads to what we call the floating-point arithmetic problem.</p>
<h2 id="heading-floating-point-arithmetic-problem">Floating-Point Arithmetic Problem</h2>
<p>In simple terms, floating-point numbers are numbers that cannot be written down exactly, so we approximate them. In a computer, this kind of approximation can lead to small precision errors, which we call the floating-point arithmetic problem.</p>
<h2 id="heading-binary-explanation">Binary Explanation</h2>
<p>Now that we've covered the simple explanation, let’s also understand this in binary terms. JavaScript handles everything in binary behind the scenes.</p>
<p>Binary is a number system that only uses two digits: 0 and 1.</p>
<h3 id="heading-why-cant-01-and-02-be-represented-exactly-in-binary">Why Can’t 0.1 and 0.2 Be Represented Exactly in Binary?</h3>
<p>The core issue is that not all decimal numbers can be perfectly represented as binary fractions.</p>
<p>Let’s take 0.1 as an example:</p>
<p>When you try to represent 0.1 in binary, you’ll find out that it can’t be expressed as a finite binary fraction. Instead, it becomes a repeating fraction, much like how 1/3 in decimal becomes 0.333..., repeating forever.</p>
<p>In binary, 0.1 becomes:</p>
<pre><code class="lang-plaintext">0.0001100110011001100110011001100110011... (repeating infinitely)
</code></pre>
<p>Since computers have limited memory, they can’t store this infinite sequence exactly. Instead, they have to cut off the number at some point, which introduces a small rounding error. This is why 0.1 in binary is only an approximation of the actual value.</p>
<p>Like 0.1, 0.2 can’t be exactly represented in binary. It becomes:</p>
<pre><code class="lang-plaintext">0.00110011001100110011001100110011... (repeating infinitely)
</code></pre>
<p>Again, the computer truncates (cutting off part of a number to fit a limit or remove extra digits) this infinite binary sequence, leading to a small error in representation.</p>
<p>So, what happens when we add 0.1 + 0.2? When you add 0.1 + 0.2 in JavaScript, the binary approximations for 0.1 and 0.2 are added together. But since both values are only approximations, the result is also an approximation.</p>
<p>Instead of getting exactly 0.3, you get something close to this:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">0.1</span> + <span class="hljs-number">0.2</span>); <span class="hljs-comment">// Output: 0.30000000000000004</span>
</code></pre>
<p>This slight error occurs because neither 0.1 nor 0.2 can be represented exactly in binary, so the final result has a small rounding error.</p>
<h2 id="heading-how-does-javascript-truncate-the-number">How Does JavaScript Truncate the Number?</h2>
<p>Now, the question arises: how does JavaScript know when to truncate the value?</p>
<p><strong>( Truncation</strong> means cutting off or shortening a number by removing extra digits beyond a certain point. <strong>)</strong></p>
<p>There’s a maximum and minimum limit for it.</p>
<p>To handle this in the computer world, we have a standard that defines how floating-point numbers are stored and calculated.</p>
<h2 id="heading-ieee-754-standard">IEEE 754 Standard</h2>
<p>JavaScript uses the IEEE 754 standard to handle floating-point arithmetic.</p>
<p>The standard defines safe integer limits for the <code>Number</code> type in JavaScript without precision loss:</p>
<ul>
<li><p><strong>Maximum Safe Integer:</strong> 2^53 - 1 or 9007199254740991</p>
</li>
<li><p><strong>Minimum Safe Integer:</strong> -(2^53 - 1) or -9007199254740991</p>
</li>
</ul>
<p>Beyond these limits, JavaScript cannot accurately represent integers due to the way floating-point arithmetic works.</p>
<p>For this reason, JavaScript provides two constants to represent these limits:</p>
<ul>
<li><p><code>Number.MAX_SAFE_INTEGER</code></p>
</li>
<li><p><code>Number.MIN_SAFE_INTEGER</code></p>
</li>
</ul>
<h3 id="heading-what-if-i-need-a-bigger-number">What If I Need a Bigger Number?</h3>
<p>If you need to work with numbers larger than the Maximum Safe Integer (like those used in cryptography or finance), JavaScript has a solution: BigInt.</p>
<h3 id="heading-enter-bigint">Enter BigInt</h3>
<p><code>BigInt</code> is a built-in object that allows you to work with whole numbers beyond the safe integer limit. It enables you to represent numbers larger than 9007199254740991, so you don't need to worry about precision errors here!</p>
<p>To use <code>BigInt</code>, simply append an <code>n</code> to the end of an integer literal:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> bigNumber = <span class="hljs-number">1234567890123456789012345678901234567890n</span>;
</code></pre>
<p>Alternatively, you can use the <code>BigInt</code> constructor:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> bigNumber = BigInt(<span class="hljs-string">"1234567890123456789012345678901234567890"</span>);
</code></pre>
<h4 id="heading-operations-with-bigint">Operations with BigInt</h4>
<p>You can perform arithmetic operations with <code>BigInt</code>, like addition, subtraction, multiplication, and even exponentiation. However, there’s a catch: you can’t mix <code>BigInt</code> with regular <code>Number</code> types in arithmetic operations without explicitly converting between them.</p>
<p>For example, this won’t work:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> result = bigNumber + <span class="hljs-number">5</span>; <span class="hljs-comment">// Error: cannot mix BigInt and other types</span>
</code></pre>
<p>You would need to convert the <code>Number</code> to <code>BigInt</code> first:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> result = bigNumber + BigInt(<span class="hljs-number">5</span>); <span class="hljs-comment">// Now it works!</span>
</code></pre>
<h3 id="heading-where-do-we-use-bigint">Where Do We Use BigInt?</h3>
<p><code>BigInt</code> is particularly useful in areas requiring precision, such as:</p>
<ul>
<li><p>Cryptographic algorithms</p>
</li>
<li><p>Handling large datasets</p>
</li>
<li><p>Financial calculations requiring exactness</p>
</li>
</ul>
<h3 id="heading-in-summary">In Summary</h3>
<ul>
<li><p>The safe integer limit in JavaScript ensures accurate number representation for integers between -(2^53 - 1) and 2^53 - 1.</p>
</li>
<li><p>Precision errors occur due to floating-point arithmetic when handling certain numbers (like 0.1 + 0.2).</p>
</li>
<li><p>If you need numbers bigger than the safe limit, <code>BigInt</code> is your friend. But remember, mixing <code>BigInt</code> and <code>Number</code> types require explicit conversions.</p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
