<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Samyak Jain</title>
    <description>The latest articles on DEV Community by Samyak Jain (@samyak112).</description>
    <link>https://dev.to/samyak112</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F939632%2F80f3a8ec-525b-45d6-91c4-c9392a80575b.jpeg</url>
      <title>DEV Community: Samyak Jain</title>
      <link>https://dev.to/samyak112</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/samyak112"/>
    <language>en</language>
    <item>
      <title>Scaling Is All You Need: Understanding sqrt(dₖ) in Self-Attention</title>
      <dc:creator>Samyak Jain</dc:creator>
      <pubDate>Tue, 11 Nov 2025 09:13:12 +0000</pubDate>
      <link>https://dev.to/samyak112/scaling-is-all-you-need-understanding-sqrtd-in-self-attention-29pk</link>
      <guid>https://dev.to/samyak112/scaling-is-all-you-need-understanding-sqrtd-in-self-attention-29pk</guid>
      <description>&lt;p&gt;Been trying to understand the scaling in the attention formula, specifically sqrt(d_k). It confused me a bit why do we need to divide at all?&lt;/p&gt;

&lt;p&gt;I was confused because we subtract each value with the max value inside softmax anyway (so exp doesn't explode our numbers), so why do we need to scale before this step as well?&lt;/p&gt;

&lt;p&gt;Turns out the difference lies between numerical stability and statistical calibration.&lt;/p&gt;

&lt;h3&gt;
  
  
  Division vs. Subtraction
&lt;/h3&gt;

&lt;p&gt;When we divide by sqrt(d_k), we're reducing the magnitude of each value proportionally, which shrinks the differences between them for example, [100, 102, 103] becomes [10.0, 10.2, 10.3], where the 2-unit and 1-unit gaps become 0.2 and 0.1. This brings the values closer together before they reach softmax.&lt;/p&gt;

&lt;p&gt;In contrast, when we subtract (like subtracting the max in softmax), we shift where the values sit on the number line without changing the differences between them at all [100, 102, 103] becomes [-3, -1, 0], but the gaps remain 2 and 1.&lt;/p&gt;

&lt;p&gt;At first, I thought: if we're just reducing magnitudes for softmax, why not simply subtract the max value like we do inside softmax for stability? But then it occurred to me that subtraction doesn't actually bring the values closer together it only shifts them.&lt;/p&gt;

&lt;h3&gt;
  
  
  Preserving Proportions for Softmax
&lt;/h3&gt;

&lt;p&gt;The problem is that I need to preserve the proportional relationships between numbers (the ratios like 102/100 = 1.02 stay the same after division), because softmax relies on these relative differences to produce meaningful probabilities. I don't want to lose how much bigger one value is compared to another.&lt;/p&gt;

&lt;p&gt;However, I also can't keep the absolute magnitude of these differences too large, because softmax's exponential would exaggerate them further turning a 3-unit spread into a distribution like [0.09, 0.24, 0.67] where one value dominates.&lt;/p&gt;

&lt;p&gt;So division is the perfect solution: it keeps the proportionality the same (10.2/10.0 = 1.02, just like before) while bringing the absolute differences closer (from 2 units to 0.2 units), ensuring values don't look way too far apart before softmax amplifies them into a more balanced distribution like [0.30, 0.33, 0.37].&lt;/p&gt;

&lt;p&gt;Another major reason is future-safe design. As d_k increases (say from 64 to 512), the dot product naturally grows larger since we're summing more terms, but this growth doesn't represent meaningful differences in attention it's just an artifact of dimensionality. By dividing by sqrt(d_k), we compensate for this growth and keep the scale consistent: whether d_k is small or large, the proportional relationships remain stable.&lt;/p&gt;

&lt;p&gt;Dividing by d_k directly would shrink values too aggressively. Using sqrt(d_k) is the right balance because the variance of the dot product grows linearly with d_k, and dividing by sqrt(d_k) keeps the standard deviation roughly constant. This ensures that the scale of the values entering softmax remains consistent, no matter the dimensionality.&lt;/p&gt;

&lt;h3&gt;
  
  
  Key Insight
&lt;/h3&gt;

&lt;p&gt;The key insight is that values need to be close together before entering softmax, so we can let softmax do the exaggeration through its exponential function in a controlled way, while subtraction just ensures numerical stability without affecting the relative distances that softmax actually cares about.&lt;/p&gt;

&lt;p&gt;Basically there are 3 important things happening here:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Division changing how far apart the values are (brings them closer)&lt;/li&gt;
&lt;li&gt;Subtraction changing where they sit on the number line (doesn't change separation)&lt;/li&gt;
&lt;li&gt;We want values close together BEFORE softmax, so softmax's exponential amplification produces a reasonable distribution, not an extreme one&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let the softmax do the exaggeration.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>machinelearning</category>
      <category>transformer</category>
    </item>
    <item>
      <title>[Boost]</title>
      <dc:creator>Samyak Jain</dc:creator>
      <pubDate>Mon, 29 Sep 2025 15:05:34 +0000</pubDate>
      <link>https://dev.to/samyak112/-paf</link>
      <guid>https://dev.to/samyak112/-paf</guid>
      <description>&lt;p&gt;

&lt;/p&gt;
&lt;div class="ltag__link--embedded"&gt;
  &lt;div class="crayons-story "&gt;
  &lt;a href="https://dev.to/samyak112/positional-encoding-sense-of-direction-for-transformers-12jp" class="crayons-story__hidden-navigation-link"&gt;Positional Encoding - Sense of direction for Transformers&lt;/a&gt;


  &lt;div class="crayons-story__body crayons-story__body-full_post"&gt;
    &lt;div class="crayons-story__top"&gt;
      &lt;div class="crayons-story__meta"&gt;
        &lt;div class="crayons-story__author-pic"&gt;

          &lt;a href="/samyak112" class="crayons-avatar  crayons-avatar--l  "&gt;
            &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F939632%2F80f3a8ec-525b-45d6-91c4-c9392a80575b.jpeg" alt="samyak112 profile" class="crayons-avatar__image"&gt;
          &lt;/a&gt;
        &lt;/div&gt;
        &lt;div&gt;
          &lt;div&gt;
            &lt;a href="/samyak112" class="crayons-story__secondary fw-medium m:hidden"&gt;
              Samyak Jain
            &lt;/a&gt;
            &lt;div class="profile-preview-card relative mb-4 s:mb-0 fw-medium hidden m:inline-block"&gt;
              
                Samyak Jain
                
              
              &lt;div id="story-author-preview-content-2874216" class="profile-preview-card__content crayons-dropdown branded-7 p-4 pt-0"&gt;
                &lt;div class="gap-4 grid"&gt;
                  &lt;div class="-mt-4"&gt;
                    &lt;a href="/samyak112" class="flex"&gt;
                      &lt;span class="crayons-avatar crayons-avatar--xl mr-2 shrink-0"&gt;
                        &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F939632%2F80f3a8ec-525b-45d6-91c4-c9392a80575b.jpeg" class="crayons-avatar__image" alt=""&gt;
                      &lt;/span&gt;
                      &lt;span class="crayons-link crayons-subtitle-2 mt-5"&gt;Samyak Jain&lt;/span&gt;
                    &lt;/a&gt;
                  &lt;/div&gt;
                  &lt;div class="print-hidden"&gt;
                    
                      Follow
                    
                  &lt;/div&gt;
                  &lt;div class="author-preview-metadata-container"&gt;&lt;/div&gt;
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/div&gt;

          &lt;/div&gt;
          &lt;a href="https://dev.to/samyak112/positional-encoding-sense-of-direction-for-transformers-12jp" class="crayons-story__tertiary fs-xs"&gt;&lt;time&gt;Sep 28 '25&lt;/time&gt;&lt;span class="time-ago-indicator-initial-placeholder"&gt;&lt;/span&gt;&lt;/a&gt;
        &lt;/div&gt;
      &lt;/div&gt;

    &lt;/div&gt;

    &lt;div class="crayons-story__indention"&gt;
      &lt;h2 class="crayons-story__title crayons-story__title-full_post"&gt;
        &lt;a href="https://dev.to/samyak112/positional-encoding-sense-of-direction-for-transformers-12jp" id="article-link-2874216"&gt;
          Positional Encoding - Sense of direction for Transformers
        &lt;/a&gt;
      &lt;/h2&gt;
        &lt;div class="crayons-story__tags"&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/machinelearning"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;machinelearning&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/programming"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;programming&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/ai"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;ai&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/architecture"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;architecture&lt;/a&gt;
        &lt;/div&gt;
      &lt;div class="crayons-story__bottom"&gt;
        &lt;div class="crayons-story__details"&gt;
          &lt;a href="https://dev.to/samyak112/positional-encoding-sense-of-direction-for-transformers-12jp" class="crayons-btn crayons-btn--s crayons-btn--ghost crayons-btn--icon-left"&gt;
            &lt;div class="multiple_reactions_aggregate"&gt;
              &lt;span class="multiple_reactions_icons_container"&gt;
                  &lt;span class="crayons_icon_container"&gt;
                    &lt;img src="https://assets.dev.to/assets/fire-f60e7a582391810302117f987b22a8ef04a2fe0df7e3258a5f49332df1cec71e.svg" width="18" height="18"&gt;
                  &lt;/span&gt;
                  &lt;span class="crayons_icon_container"&gt;
                    &lt;img src="https://assets.dev.to/assets/multi-unicorn-b44d6f8c23cdd00964192bedc38af3e82463978aa611b4365bd33a0f1f4f3e97.svg" width="18" height="18"&gt;
                  &lt;/span&gt;
                  &lt;span class="crayons_icon_container"&gt;
                    &lt;img src="https://assets.dev.to/assets/sparkle-heart-5f9bee3767e18deb1bb725290cb151c25234768a0e9a2bd39370c382d02920cf.svg" width="18" height="18"&gt;
                  &lt;/span&gt;
              &lt;/span&gt;
              &lt;span class="aggregate_reactions_counter"&gt;5&lt;span class="hidden s:inline"&gt; reactions&lt;/span&gt;&lt;/span&gt;
            &lt;/div&gt;
          &lt;/a&gt;
            &lt;a href="https://dev.to/samyak112/positional-encoding-sense-of-direction-for-transformers-12jp#comments" class="crayons-btn crayons-btn--s crayons-btn--ghost crayons-btn--icon-left flex items-center"&gt;
              Comments


              2&lt;span class="hidden s:inline"&gt; comments&lt;/span&gt;
            &lt;/a&gt;
        &lt;/div&gt;
        &lt;div class="crayons-story__save"&gt;
          &lt;small class="crayons-story__tertiary fs-xs mr-2"&gt;
            11 min read
          &lt;/small&gt;
            
              &lt;span class="bm-initial"&gt;
                

              &lt;/span&gt;
              &lt;span class="bm-success"&gt;
                

              &lt;/span&gt;
            
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;/div&gt;




</description>
      <category>machinelearning</category>
      <category>programming</category>
      <category>ai</category>
      <category>architecture</category>
    </item>
    <item>
      <title>Positional Encoding - Sense of direction for Transformers</title>
      <dc:creator>Samyak Jain</dc:creator>
      <pubDate>Sun, 28 Sep 2025 11:29:08 +0000</pubDate>
      <link>https://dev.to/samyak112/positional-encoding-sense-of-direction-for-transformers-12jp</link>
      <guid>https://dev.to/samyak112/positional-encoding-sense-of-direction-for-transformers-12jp</guid>
      <description>&lt;p&gt;I have been trying to understand how transformers work lately, and whenever we read or hear about transformers, there is one word which comes up more than any other: ‘Attention’ , although it’s not something that first appeared with transformers, but it has become the centerpiece of the whole architecture.&lt;/p&gt;

&lt;p&gt;That said, attention by itself doesn’t get us very far. There’s another idea that doesn’t always get the same spotlight, but without it, self-attention would completely fall apart. That idea is &lt;strong&gt;positional encoding&lt;/strong&gt; the thing that lets transformers keep track of word order.&lt;/p&gt;

&lt;p&gt;But why self attention in transformers is useless without this Positional encoding?&lt;/p&gt;

&lt;p&gt;The issue is that self-attention has no built-in sense of order. Each token looks at every other token simultaneously, like in the diagram from 3Blue1Brown.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa0ac0jp1mtn82b28aftq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa0ac0jp1mtn82b28aftq.png" alt="Image showing self attention in Transformer , from 3blue1brown youtube channel video illustration"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now because each token (approximately a word) is looking at each token at the same time there is no information of how far a token is to another token or whats the order of the tokens.&lt;/p&gt;

&lt;p&gt;So if my sentence is “A cat ran behind a mouse,” the transformer without positional encoding would only see it as a bag of words: {A, cat, ran, behind, a, mouse}. Now flip it to “A mouse ran behind a cat” — the bag looks identical to a positional encoding less transformer. The meaning, however, is completely different. That’s the blind spot positional encoding is designed to fix.&lt;/p&gt;

&lt;p&gt;This wasn’t really a problem for RNNs, because the architecture itself processed tokens step by step. Each word was fed in after the previous one, and the hidden state carried along a memory of everything seen so far. In other words, the order of the sequence was baked into the way RNNs worked.&lt;/p&gt;

&lt;p&gt;Transformers flipped that idea. Instead of moving sequentially, they looked at all the tokens in parallel. That parallelism is one of the reasons that makes them so powerful and efficient — but it also means they lose the natural sense of order that RNNs had for free.&lt;/p&gt;

&lt;p&gt;That’s where the positional encoding steps in: it reintroduces the concept of order without giving up the transformer’s parallelism.&lt;/p&gt;

&lt;p&gt;So how do we encode this "sense" of position in each token?&lt;/p&gt;

&lt;p&gt;Well if you look at the original "Attention is all you need" paper they have solved this problem using these two formula&lt;/p&gt;

&lt;p&gt;

&lt;/p&gt;
&lt;div class="katex-element"&gt;
  &lt;span class="katex-display"&gt;&lt;span class="katex"&gt;&lt;span class="katex-mathml"&gt;PE(pos,2i)=sin⁡(pos100002i/dmodel)
PE_{(pos, 2i)} = \sin\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right)
&lt;/span&gt;&lt;span class="katex-html"&gt;&lt;span class="base"&gt;&lt;span class="strut"&gt;&lt;/span&gt;&lt;span class="mord mathnormal"&gt;P&lt;/span&gt;&lt;span class="mord"&gt;&lt;span class="mord mathnormal"&gt;E&lt;/span&gt;&lt;span class="msupsub"&gt;&lt;span class="vlist-t vlist-t2"&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;span class="pstrut"&gt;&lt;/span&gt;&lt;span class="sizing reset-size6 size3 mtight"&gt;&lt;span class="mord mtight"&gt;&lt;span class="mopen mtight"&gt;(&lt;/span&gt;&lt;span class="mord mathnormal mtight"&gt;p&lt;/span&gt;&lt;span class="mord mathnormal mtight"&gt;os&lt;/span&gt;&lt;span class="mpunct mtight"&gt;,&lt;/span&gt;&lt;span class="mord mtight"&gt;2&lt;/span&gt;&lt;span class="mord mathnormal mtight"&gt;i&lt;/span&gt;&lt;span class="mclose mtight"&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-s"&gt;​&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="mspace"&gt;&lt;/span&gt;&lt;span class="mrel"&gt;=&lt;/span&gt;&lt;span class="mspace"&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="base"&gt;&lt;span class="strut"&gt;&lt;/span&gt;&lt;span class="mop"&gt;sin&lt;/span&gt;&lt;span class="mspace"&gt;&lt;/span&gt;&lt;span class="minner"&gt;&lt;span class="mopen delimcenter"&gt;&lt;span class="delimsizing size2"&gt;(&lt;/span&gt;&lt;/span&gt;&lt;span class="mord"&gt;&lt;span class="mopen nulldelimiter"&gt;&lt;/span&gt;&lt;span class="mfrac"&gt;&lt;span class="vlist-t vlist-t2"&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;span class="pstrut"&gt;&lt;/span&gt;&lt;span class="mord"&gt;&lt;span class="mord"&gt;1000&lt;/span&gt;&lt;span class="mord"&gt;&lt;span class="mord"&gt;0&lt;/span&gt;&lt;span class="msupsub"&gt;&lt;span class="vlist-t"&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;span class="pstrut"&gt;&lt;/span&gt;&lt;span class="sizing reset-size6 size3 mtight"&gt;&lt;span class="mord mtight"&gt;&lt;span class="mord mtight"&gt;2&lt;/span&gt;&lt;span class="mord mathnormal mtight"&gt;i&lt;/span&gt;&lt;span class="mord mtight"&gt;/&lt;/span&gt;&lt;span class="mord mtight"&gt;&lt;span class="mord mathnormal mtight"&gt;d&lt;/span&gt;&lt;span class="msupsub"&gt;&lt;span class="vlist-t vlist-t2"&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;span class="pstrut"&gt;&lt;/span&gt;&lt;span class="sizing reset-size3 size1 mtight"&gt;&lt;span class="mord mtight"&gt;&lt;span class="mord text mtight"&gt;&lt;span class="mord mtight"&gt;model&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-s"&gt;​&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span&gt;&lt;span class="pstrut"&gt;&lt;/span&gt;&lt;span class="frac-line"&gt;&lt;/span&gt;&lt;/span&gt;&lt;span&gt;&lt;span class="pstrut"&gt;&lt;/span&gt;&lt;span class="mord"&gt;&lt;span class="mord mathnormal"&gt;p&lt;/span&gt;&lt;span class="mord mathnormal"&gt;os&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-s"&gt;​&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="mclose nulldelimiter"&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="mclose delimcenter"&gt;&lt;span class="delimsizing size2"&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;
&lt;/div&gt;



&lt;div class="katex-element"&gt;
  &lt;span class="katex-display"&gt;&lt;span class="katex"&gt;&lt;span class="katex-mathml"&gt;PE(pos,2i+1)=cos⁡(pos100002i/dmodel)
PE_{(pos, 2i+1)} = \cos\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right)
&lt;/span&gt;&lt;span class="katex-html"&gt;&lt;span class="base"&gt;&lt;span class="strut"&gt;&lt;/span&gt;&lt;span class="mord mathnormal"&gt;P&lt;/span&gt;&lt;span class="mord"&gt;&lt;span class="mord mathnormal"&gt;E&lt;/span&gt;&lt;span class="msupsub"&gt;&lt;span class="vlist-t vlist-t2"&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;span class="pstrut"&gt;&lt;/span&gt;&lt;span class="sizing reset-size6 size3 mtight"&gt;&lt;span class="mord mtight"&gt;&lt;span class="mopen mtight"&gt;(&lt;/span&gt;&lt;span class="mord mathnormal mtight"&gt;p&lt;/span&gt;&lt;span class="mord mathnormal mtight"&gt;os&lt;/span&gt;&lt;span class="mpunct mtight"&gt;,&lt;/span&gt;&lt;span class="mord mtight"&gt;2&lt;/span&gt;&lt;span class="mord mathnormal mtight"&gt;i&lt;/span&gt;&lt;span class="mbin mtight"&gt;+&lt;/span&gt;&lt;span class="mord mtight"&gt;1&lt;/span&gt;&lt;span class="mclose mtight"&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-s"&gt;​&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="mspace"&gt;&lt;/span&gt;&lt;span class="mrel"&gt;=&lt;/span&gt;&lt;span class="mspace"&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="base"&gt;&lt;span class="strut"&gt;&lt;/span&gt;&lt;span class="mop"&gt;cos&lt;/span&gt;&lt;span class="mspace"&gt;&lt;/span&gt;&lt;span class="minner"&gt;&lt;span class="mopen delimcenter"&gt;&lt;span class="delimsizing size2"&gt;(&lt;/span&gt;&lt;/span&gt;&lt;span class="mord"&gt;&lt;span class="mopen nulldelimiter"&gt;&lt;/span&gt;&lt;span class="mfrac"&gt;&lt;span class="vlist-t vlist-t2"&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;span class="pstrut"&gt;&lt;/span&gt;&lt;span class="mord"&gt;&lt;span class="mord"&gt;1000&lt;/span&gt;&lt;span class="mord"&gt;&lt;span class="mord"&gt;0&lt;/span&gt;&lt;span class="msupsub"&gt;&lt;span class="vlist-t"&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;span class="pstrut"&gt;&lt;/span&gt;&lt;span class="sizing reset-size6 size3 mtight"&gt;&lt;span class="mord mtight"&gt;&lt;span class="mord mtight"&gt;2&lt;/span&gt;&lt;span class="mord mathnormal mtight"&gt;i&lt;/span&gt;&lt;span class="mord mtight"&gt;/&lt;/span&gt;&lt;span class="mord mtight"&gt;&lt;span class="mord mathnormal mtight"&gt;d&lt;/span&gt;&lt;span class="msupsub"&gt;&lt;span class="vlist-t vlist-t2"&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;span class="pstrut"&gt;&lt;/span&gt;&lt;span class="sizing reset-size3 size1 mtight"&gt;&lt;span class="mord mtight"&gt;&lt;span class="mord text mtight"&gt;&lt;span class="mord mtight"&gt;model&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-s"&gt;​&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span&gt;&lt;span class="pstrut"&gt;&lt;/span&gt;&lt;span class="frac-line"&gt;&lt;/span&gt;&lt;/span&gt;&lt;span&gt;&lt;span class="pstrut"&gt;&lt;/span&gt;&lt;span class="mord"&gt;&lt;span class="mord mathnormal"&gt;p&lt;/span&gt;&lt;span class="mord mathnormal"&gt;os&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-s"&gt;​&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="mclose nulldelimiter"&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="mclose delimcenter"&gt;&lt;span class="delimsizing size2"&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;
&lt;/div&gt;


&lt;p&gt;Haha this didn't really made a lot of sense to me at the first glance , So I'll try to explain what I have understood about it so far.&lt;/p&gt;

&lt;p&gt;I had questions like how this formula is derived? why there is a pair of sine and cosine? whats with using 10,000? So Lets try to reach to this formula step by step.&lt;/p&gt;

&lt;h4&gt;
  
  
  Idea 1: Just Count (Integer Indexing)
&lt;/h4&gt;

&lt;p&gt;The simplest idea to have positional information is to assign each token its index in the sequence.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;The Idea:&lt;/strong&gt; The first word is 1, the second is 2, the third is 3, and so on. &lt;code&gt;[1, 2, 3, 4, ...]&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;The Flaw:&lt;/strong&gt; The numbers can become very large for long sentences. Neural networks work best with small, normalized values, and large numbers can make training unstable. Also, a model might see very different ranges of numbers during training vs. testing, making it hard to generalize.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ok so we cant have direct integers as its not Neural network friendly , it can cause vanishing or exploding gradient. Normally neural networks like their values to be balanced between positive and negative values.&lt;/p&gt;

&lt;h4&gt;
  
  
  Idea 2: Normalize the Count
&lt;/h4&gt;

&lt;p&gt;To fix the scaling issue, the next logical step is to normalize the indices to a fixed range, like &lt;code&gt;[0, 1]&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;The Idea:&lt;/strong&gt; Divide each index by the length of the sentence. For a 4-word sentence, the encoding would be: &lt;code&gt;[1/4, 2/4, 3/4, 4/4]&lt;/code&gt; or &lt;code&gt;[0.25, 0.5, 0.75, 1.0]&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;The Flaw:&lt;/strong&gt; This makes the meaning of a position dependent on the sentence length. For example, the value &lt;code&gt;0.5&lt;/code&gt; means the 2nd position in a 4-word sentence, but it would mean the 10th position in a 20-word sentence. The model has no consistent way to interpret what a position value means, which is a deal-breaker.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ok so we need static information which represents a position it cant be dependent on the length of the sentence or some other variable factor.&lt;/p&gt;

&lt;h4&gt;
  
  
  Idea 3: Use a Binary Vector
&lt;/h4&gt;

&lt;p&gt;To handle arbitrary lengths consistently while keeping values small, the next idea is to represent the position index in binary and turn it into a vector.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;The Idea:&lt;/strong&gt; Represent each number with its binary equivalent, creating a vector for each position. Here we solved the previous two problems which were keeping the values between 0 and 1 and keeping the information static regardless of the length of sentence (still all the numbers are positive though).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Position 2 -&amp;gt; &lt;code&gt;[0, 0, 1, 0]&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Position 3 -&amp;gt; &lt;code&gt;[0, 0, 1, 1]&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Position 4 -&amp;gt; &lt;code&gt;[0, 1, 0, 0]&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;strong&gt;The Flaw:&lt;/strong&gt; This is discrete and "jagged." A small change in position (e.g., from 7 (&lt;code&gt;0111&lt;/code&gt;) to 8 (&lt;code&gt;1000&lt;/code&gt;)) can cause every single value in the vector to flip. This gives the model no smooth, continuous sense of distance or proximity between nearby positions.&lt;/p&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;Below is an example of what it means by "jagged"&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0xs3wa6kae8pvtxv0m5f.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0xs3wa6kae8pvtxv0m5f.png" alt="example of what it means with "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Checkout the source &lt;a href="https://huggingface.co/blog/designing-positional-encoding#:~:text=We%27ve%20solved%20the%20value%20range%20problem%2C%20and%20we%20now%20have%20unique%20encodings%20that%20are%20consistent%20across%20different%20sequence%20lengths.%20What%20happens%20if%20we%20plot%20a%20low%20dimensional%20version%20of%20our%20token%20embedding%20and%20visualize%20the%20addition%20of%20our%20binary%20positional%20vector%20for%20different%20values." rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Ok so we want that our model gets a smooth curve not an abrupt change between two adjacent positions.&lt;/p&gt;

&lt;h3&gt;
  
  
  Idea 4: Using Sine Waves
&lt;/h3&gt;

&lt;p&gt;Alright so we need something which is smooth, meaning it periodically changes from 0 to 1 to 0 and so on, well sine function can perform this perfectly and its also in the range of [-1,1], which solves our problem of having equal positive and negatives.&lt;/p&gt;

&lt;p&gt;Like this &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmclmwlku1wff39x2skha.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmclmwlku1wff39x2skha.png" alt="Illustration of using sin waves for positional encoding"&gt;&lt;/a&gt;&lt;br&gt;
Checkout the source &lt;a href="https://huggingface.co/blog/designing-positional-encoding#:~:text=The%20above%20animation%20visualizes%20our%20position%20embedding%20if%20each%20component%20is%20alternatively%20drawn%20from" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Alright lets try to use a sin function to calculate positions for our tokens&lt;/p&gt;

&lt;p&gt;Does this sine wave approach checks all the problems that we found in other approaches?&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;something which gives out a smooth curve&lt;/li&gt;
&lt;li&gt;would be static irrespective of the length of the sequence&lt;/li&gt;
&lt;li&gt;not integers so wont cause problems for the neural network&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is a very brief version which tries to derive the formula but it has been explained in a very well manner &lt;a href="https://towardsdatascience.com/master-positional-encoding-part-i-63c05d90a0c3/?utm_source=chatgpt.com" rel="noopener noreferrer"&gt;here&lt;/a&gt; and &lt;a href="https://huggingface.co/blog/designing-positional-encoding" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Alright, does that mean we’re all set now? We would just use one sine function per position and call it a day?&lt;/p&gt;

&lt;p&gt;Well... not exactly &lt;/p&gt;
&lt;h4&gt;
  
  
  1. Periodicity problem
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Sine is &lt;strong&gt;periodic&lt;/strong&gt;, which means it repeats its values over and over.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;For example, if we move along the sine wave by 1 radian per position:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;sin(1)&lt;/code&gt;, &lt;code&gt;sin(2)&lt;/code&gt;, …&lt;/li&gt;
&lt;li&gt;By the time we reach &lt;code&gt;sin(6)&lt;/code&gt;, the value is already &lt;strong&gt;very close to what we had earlier&lt;/strong&gt;, just because sine repeats.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;This creates a problem: the model sees &lt;strong&gt;almost the same number at different positions&lt;/strong&gt;, even though they are far apart in the sequence. It can’t reliably tell positions apart.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;
  
  
  2. Phase problem
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Even without worrying about repetition, &lt;strong&gt;phase ambiguity&lt;/strong&gt; is an issue.&lt;/li&gt;
&lt;li&gt;Consider &lt;code&gt;sin(30)&lt;/code&gt; and &lt;code&gt;sin(150)&lt;/code&gt;. Both return roughly 0.5.&lt;/li&gt;
&lt;li&gt;For the model, if you only provide the sine value, it sees &lt;strong&gt;0.5&lt;/strong&gt; and has &lt;strong&gt;no idea whether it came from position 30 or 150&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;This is why &lt;strong&gt;sine alone doesn’t uniquely identify positions&lt;/strong&gt; — the same value can appear at many different points in the sequence.&lt;/li&gt;
&lt;li&gt;You cant locate a point in a 2d space just with a y axis (sine)&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;
  
  
  3. Linear Transformation
&lt;/h4&gt;

&lt;p&gt;Another major problem is &lt;strong&gt;linear transformation&lt;/strong&gt;. You might think that moving from &lt;code&gt;pos = 6&lt;/code&gt; to &lt;code&gt;pos = 9&lt;/code&gt; should be equivalent to moving from &lt;code&gt;pos = 18&lt;/code&gt; to &lt;code&gt;pos = 21&lt;/code&gt;, because the &lt;strong&gt;offset &lt;code&gt;k = 3&lt;/code&gt; is the same&lt;/strong&gt;. But it wont happen with the current approach&lt;/p&gt;

&lt;p&gt;But before we look at why it wont happen lets understand why we want this property? This is very well explained in a blog that am quoting here&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Why is this a very desirable property to have? Imagine we have a network that is trying to translate the sentence "I am going to eat."&lt;/p&gt;

&lt;p&gt;The combination "is/am/are" +"going"+"to" +"verb" is a very common grammatical structure, with a fixed positional structure. "going" always ends up at index 1, "to" at index 2, etc. &lt;/p&gt;

&lt;p&gt;In this case, when translating "verb", we may want the network to learn to pay attention to the noun "I" that occurs before "am going to". "I" is located 4 position units to the left of "verb".&lt;/p&gt;

&lt;p&gt;Since our attention layer uses linear transformations to form the keys, queries, and values, it would be nice if we have positional encodings such that the linear transformation can translate the position vector located 4 units to the left, so that it lines up with the position vector of "verb". &lt;/p&gt;

&lt;p&gt;The query and key would then match up perfectly.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Checkout the source &lt;a href="https://towardsdatascience.com/master-positional-encoding-part-i-63c05d90a0c3/?utm_source=chatgpt.com#:~:text=Why%20is%20this%20a%20very%20desirable%20property%20to%20have%3F" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;However, when you use &lt;strong&gt;only sine values&lt;/strong&gt; in positional encoding, this isn’t true. Here’s why:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Sine depends on absolute position&lt;/strong&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- Sine is a wave that oscillates between -1 and 1.
- The amount the sine value changes when you move by `k` depends on **where you start** on the wave.
- For example, moving 3 steps near a peak of the wave might produce a tiny change, while moving 3 steps near zero might produce a large change.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Shift is not consistent&lt;/strong&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- The same offset `k` produces **different differences in sine values** depending on the starting position.
- That means the “distance” between `pos` and `pos+k` is **variable**, unlike what you might expect from a true linear transformation.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Consequence&lt;/strong&gt;:&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- Moving by the same offset doesn’t give the same change in information.
- The sine-only encoding is **position-dependent**, so relative shifts aren’t uniform across the sequence.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;For an illustration checkout this video&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpnqvjtq8r85c032c9v7j.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpnqvjtq8r85c032c9v7j.gif" alt="Illustration of using sine only and sine + cosine offset"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;
  
  
  Enter Sin + Cos based embeddings
&lt;/h3&gt;

&lt;p&gt;We are close to the formula that the paper discussed, so we saw that sine based embeddings even though provided us with smooth curve it had its own problems.&lt;/p&gt;

&lt;p&gt;Lets see if we can solve those problems with sin + cos&lt;/p&gt;

&lt;p&gt;Each position is now represented as a &lt;strong&gt;pair &lt;code&gt;[sin(f*pos), cos(f*pos)]&lt;/code&gt;&lt;/strong&gt; for each frequency.&lt;/p&gt;
&lt;h4&gt;
  
  
  &lt;strong&gt;Unique positions:&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;The combination of sine and cosine gives a &lt;strong&gt;unique point on the circle&lt;/strong&gt; for every position.&lt;/p&gt;

&lt;p&gt;Earlier, using &lt;strong&gt;sine alone&lt;/strong&gt;, we ran into the &lt;strong&gt;phase problem&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;sin(30°) ≈ 0.5&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;sin(150°) ≈ 0.5&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The model would see &lt;strong&gt;0.5&lt;/strong&gt; in both cases and wouldn’t know whether it came from position 30 or 150 — clearly a problem!&lt;/p&gt;

&lt;p&gt;Now, with &lt;strong&gt;sin + cos&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Represent position as a &lt;strong&gt;2D point&lt;/strong&gt;: &lt;code&gt;[sin(pos), cos(pos)]&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Example:&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Position&lt;/th&gt;
&lt;th&gt;sin(pos)&lt;/th&gt;
&lt;th&gt;cos(pos)&lt;/th&gt;
&lt;th&gt;Point (sin, cos)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;30°&lt;/td&gt;
&lt;td&gt;0.5&lt;/td&gt;
&lt;td&gt;0.866&lt;/td&gt;
&lt;td&gt;(0.5, 0.866)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;150°&lt;/td&gt;
&lt;td&gt;0.5&lt;/td&gt;
&lt;td&gt;-0.866&lt;/td&gt;
&lt;td&gt;(0.5, -0.866)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Even though the sine values are the same, the &lt;strong&gt;cosine values are different&lt;/strong&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The points &lt;code&gt;(0.5, 0.866)&lt;/code&gt; and &lt;code&gt;(0.5, -0.866)&lt;/code&gt; are &lt;strong&gt;distinct on the circle&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;The model can now &lt;strong&gt;tell these positions apart&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So, combining sine and cosine &lt;strong&gt;removes the ambiguity&lt;/strong&gt; and makes each position uniquely identifiable on the circle.&lt;/p&gt;
&lt;h4&gt;
  
  
  Periodicity Problem
&lt;/h4&gt;

&lt;p&gt;The sine + cosine pairs doesnt directly helps in solving this problem, i think the creators just delayed this problem by creating multiple pairs of sin and cos (dimensions = d_model) and on top of that this explains why they used the scaling of 10,000 -&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Using a &lt;strong&gt;large number like 10,000&lt;/strong&gt; spreads the frequencies &lt;strong&gt;logarithmically&lt;/strong&gt; across dimensions.&lt;/li&gt;
&lt;li&gt;Low dimensions oscillate fast, high dimensions oscillate slowly.&lt;/li&gt;
&lt;li&gt;Because of this spread, the combined vector of &lt;code&gt;[sin, cos]&lt;/code&gt; across all dimensions is &lt;strong&gt;very unlikely to repeat for nearby positions&lt;/strong&gt;, even though each individual sine/cosine is periodic.&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;
  
  
  Linear Transformation
&lt;/h4&gt;

&lt;p&gt;Now, each position is represented as &lt;strong&gt;two numbers&lt;/strong&gt;: &lt;code&gt;[sin(f * pos), cos(f * pos)]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Think of this as a &lt;strong&gt;point on a circle&lt;/strong&gt;, where the angle = &lt;code&gt;f * pos&lt;/code&gt;.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- `sin(f * pos)` = vertical coordinate        
- `cos(f * pos)` = horizontal coordinate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h5&gt;
  
  
  How shifting positions works
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Moving by &lt;code&gt;k&lt;/code&gt; positions = increasing the angle by &lt;code&gt;f * k&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;In 2D, this is equivalent to &lt;strong&gt;rotating the point around the circle&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;A rotation has a &lt;strong&gt;fixed 2×2 matrix&lt;/strong&gt;:&lt;/li&gt;
&lt;/ul&gt;


&lt;div class="katex-element"&gt;
  &lt;span class="katex-display"&gt;&lt;span class="katex"&gt;&lt;span class="katex-mathml"&gt;PEpos=[sin⁡(f⋅pos) cos⁡(f⋅pos)]
\mathbf{PE}_{pos} =
\begin{bmatrix}
\sin(f \cdot pos) \
\cos(f \cdot pos)
\end{bmatrix}
&lt;/span&gt;&lt;span class="katex-html"&gt;&lt;span class="base"&gt;&lt;span class="strut"&gt;&lt;/span&gt;&lt;span class="mord"&gt;&lt;span class="mord"&gt;&lt;span class="mord mathbf"&gt;PE&lt;/span&gt;&lt;/span&gt;&lt;span class="msupsub"&gt;&lt;span class="vlist-t vlist-t2"&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;span class="pstrut"&gt;&lt;/span&gt;&lt;span class="sizing reset-size6 size3 mtight"&gt;&lt;span class="mord mtight"&gt;&lt;span class="mord mathnormal mtight"&gt;p&lt;/span&gt;&lt;span class="mord mathnormal mtight"&gt;os&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-s"&gt;​&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="mspace"&gt;&lt;/span&gt;&lt;span class="mrel"&gt;=&lt;/span&gt;&lt;span class="mspace"&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="base"&gt;&lt;span class="strut"&gt;&lt;/span&gt;&lt;span class="minner"&gt;&lt;span class="mopen delimcenter"&gt;&lt;span class="delimsizing size1"&gt;[&lt;/span&gt;&lt;/span&gt;&lt;span class="mord"&gt;&lt;span class="mtable"&gt;&lt;span class="col-align-c"&gt;&lt;span class="vlist-t vlist-t2"&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;span class="pstrut"&gt;&lt;/span&gt;&lt;span class="mord"&gt;&lt;span class="mop"&gt;sin&lt;/span&gt;&lt;span class="mopen"&gt;(&lt;/span&gt;&lt;span class="mord mathnormal"&gt;f&lt;/span&gt;&lt;span class="mspace"&gt;&lt;/span&gt;&lt;span class="mbin"&gt;⋅&lt;/span&gt;&lt;span class="mspace"&gt;&lt;/span&gt;&lt;span class="mord mathnormal"&gt;p&lt;/span&gt;&lt;span class="mord mathnormal"&gt;os&lt;/span&gt;&lt;span class="mclose"&gt;)&lt;/span&gt;&lt;span class="mspace"&gt; &lt;/span&gt;&lt;span class="mspace"&gt;&lt;/span&gt;&lt;span class="mop"&gt;cos&lt;/span&gt;&lt;span class="mopen"&gt;(&lt;/span&gt;&lt;span class="mord mathnormal"&gt;f&lt;/span&gt;&lt;span class="mspace"&gt;&lt;/span&gt;&lt;span class="mbin"&gt;⋅&lt;/span&gt;&lt;span class="mspace"&gt;&lt;/span&gt;&lt;span class="mord mathnormal"&gt;p&lt;/span&gt;&lt;span class="mord mathnormal"&gt;os&lt;/span&gt;&lt;span class="mclose"&gt;)&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-s"&gt;​&lt;/span&gt;&lt;/span&gt;&lt;span class="vlist-r"&gt;&lt;span class="vlist"&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;span class="mclose delimcenter"&gt;&lt;span class="delimsizing size1"&gt;]&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;
&lt;/div&gt;


&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Key point:&lt;/strong&gt; this matrix &lt;strong&gt;depends only on k&lt;/strong&gt;, not on the starting position.&lt;/li&gt;
&lt;/ul&gt;




&lt;h3&gt;
  
  
  Why this solves linear transformation
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Uniform distance changes&lt;/strong&gt;    &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The Euclidean distance between a point and its rotated version is &lt;strong&gt;constant&lt;/strong&gt; for a given k&lt;/li&gt;
&lt;li&gt;No matter where you start, moving forward by k produces the same shift in the vector&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Predictable relative shifts&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Because rotation is linear, the model can &lt;strong&gt;learn a fixed transformation for any offset k&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;This is exactly what the Transformer exploits to reason about relative positions&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Intuition&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Sine-only = wavy line → inconsistent movement&lt;/li&gt;
&lt;li&gt;Sin+cos = circle → rotation → consistent movement&lt;/li&gt;
&lt;/ol&gt;


&lt;/li&gt;

&lt;/ol&gt;

&lt;p&gt;This concept of linear transformation in PE is very well explained &lt;a href="https://blog.timodenk.com/linear-relationships-in-the-transformers-positional-encoding/" rel="noopener noreferrer"&gt;here&lt;/a&gt; and &lt;a href="https://kazemnejad.com/blog/transformer_architecture_positional_encoding/" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Experiment
&lt;/h3&gt;

&lt;p&gt;To see the difference in practice, I created positional embeddings in two ways:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Sine-only embeddings&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Sine + Cosine pairs&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I then computed the &lt;strong&gt;cosine similarity&lt;/strong&gt; between two pairs of positions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Pair 1:&lt;/strong&gt; &lt;code&gt;pos = 5&lt;/code&gt; and &lt;code&gt;pos = 9&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Pair 2:&lt;/strong&gt; &lt;code&gt;pos = 13&lt;/code&gt; and &lt;code&gt;pos = 17&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both pairs have the &lt;strong&gt;same offset&lt;/strong&gt; (&lt;code&gt;Δpos = 4&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Results:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Sine-only embeddings:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The cosine similarity for Pair 1 was &lt;strong&gt;different&lt;/strong&gt; from Pair 2.&lt;/li&gt;
&lt;li&gt;This confirms that sine-only embeddings produce &lt;strong&gt;variable shifts&lt;/strong&gt; depending on the starting position.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;&lt;strong&gt;Sine + Cos embeddings:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The cosine similarity for Pair 1 &lt;strong&gt;exactly matched&lt;/strong&gt; Pair 2.&lt;/li&gt;
&lt;li&gt;Using &lt;code&gt;[sin, cos]&lt;/code&gt; ensures that &lt;strong&gt;shifts are consistent&lt;/strong&gt; across the sequence, independent of the starting position.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://colab.research.google.com/drive/1bYJkqSDdfWqXa_KUQvoKXn1cJyV1WAVc?usp=sharing" rel="noopener noreferrer"&gt;Here&lt;/a&gt; is the google Colab to check this experiment out&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;So yeah, positional encoding might not get the same spotlight as attention, but it’s what keeps transformers from being just a fancy bag-of-words model. We went from simple counting to sine waves and then to sine + cosine pairs, and along the way, we saw why each step mattered. In the end, sin + cos gives each position a unique spot on a circle, solves phase issues, and makes relative shifts predictable—letting the model actually make sense of word order while still enjoying the parallelism that makes transformers so powerful.&lt;/p&gt;

&lt;p&gt;Positional encoding is still an active area of research. People are exploring relative positional encodings instead of static ones, like we discussed—check it out &lt;a href="https://arxiv.org/pdf/1803.02155" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;There are still models like autoregressive models which runs fine without using Positional encoding at all, which makes this topic even more interesting that when do we need to use Positional encodings and when not, but still need to read a lot before I can try to explain it in my own words.&lt;/p&gt;

&lt;p&gt;Since this topic is really vast, I’d love for readers to critique this blog and point out any mistakes I might have made or assumptions that could be wrong.&lt;/p&gt;

&lt;p&gt;References&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://towardsdatascience.com/master-positional-encoding-part-i-63c05d90a0c3" rel="noopener noreferrer"&gt;https://towardsdatascience.com/master-positional-encoding-part-i-63c05d90a0c3&lt;/a&gt; - this one derives the Positional embeddings starting starting from just indexes&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://blog.timodenk.com/linear-relationships-in-the-transformers-positional-encoding/" rel="noopener noreferrer"&gt;https://blog.timodenk.com/linear-relationships-in-the-transformers-positional-encoding/&lt;/a&gt; - helped me understand the linear transformation reasoning&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://huggingface.co/blog/designing-positional-encoding" rel="noopener noreferrer"&gt;https://huggingface.co/blog/designing-positional-encoding&lt;/a&gt; - Another great blog which derives the Positional embeddings starting from just indexes&lt;/li&gt;
&lt;li&gt;&lt;a href="https://naokishibuya.github.io/blog/2021-10-31-transformers-positional-encoding" rel="noopener noreferrer"&gt;https://naokishibuya.github.io/blog/2021-10-31-transformers-positional-encoding&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://kazemnejad.com/blog/transformer_architecture_positional_encoding/" rel="noopener noreferrer"&gt;https://kazemnejad.com/blog/transformer_architecture_positional_encoding/&lt;/a&gt; - &lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>machinelearning</category>
      <category>programming</category>
      <category>ai</category>
      <category>architecture</category>
    </item>
    <item>
      <title>Understanding SVD's Intuition (Singular Value Decomposition)</title>
      <dc:creator>Samyak Jain</dc:creator>
      <pubDate>Mon, 12 May 2025 05:36:51 +0000</pubDate>
      <link>https://dev.to/samyak112/understanding-svds-intuition-singular-value-decomposition-28ak</link>
      <guid>https://dev.to/samyak112/understanding-svds-intuition-singular-value-decomposition-28ak</guid>
      <description>&lt;h3&gt;
  
  
  What is SVD
&lt;/h3&gt;

&lt;p&gt;Singular Value Decomposition (SVD) is a fundamental matrix factorisation technique in linear algebra that decomposes a matrix into three simpler component matrices. It's incredibly versatile and powerful, serving as the backbone for numerous applications across various fields.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why Was SVD Developed?
&lt;/h3&gt;

&lt;p&gt;SVD was developed to solve the problem of finding the best approximation of a matrix by a lower-rank matrix. Mathematicians needed a way to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Factorise&lt;/strong&gt; the original matrix into three smaller matrices that capture hidden relationship , It will find latent features that explain the patterns in a given matrix.&lt;/li&gt;
&lt;li&gt;Understand the fundamental structure of linear transformations.&lt;/li&gt;
&lt;li&gt;Analyse the underlying properties of matrices regardless of their dimensions.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The core purpose was to find a way to decompose any matrix into simpler, more manageable components that reveal its essential properties - specifically its rank, range (column space), and null space.&lt;/p&gt;

&lt;h4&gt;
  
  
  What does it mean to find the best approximation of a matrix by a lower-rank matrix?
&lt;/h4&gt;

&lt;p&gt;When we have a large, complex matrix A with rank r, we often want to simplify it to save computational resources while preserving as much of the original information as possible.&lt;/p&gt;

&lt;p&gt;Finding the "best approximation" means:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Creating a new matrix Â with lower rank k (where k &amp;lt; r)&lt;/li&gt;
&lt;li&gt;Ensuring this approximation minimises the error (typically measured as the Frobenius norm ||A - Â||)&lt;/li&gt;
&lt;li&gt;Capturing the most important patterns/structures in the original data&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is valuable because lower-rank matrices:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Require less storage space&lt;/li&gt;
&lt;li&gt;Allow faster computations&lt;/li&gt;
&lt;li&gt;Often filter out noise while preserving signal&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  What is a &lt;em&gt;Latent Feature&lt;/em&gt;?
&lt;/h3&gt;

&lt;p&gt;A &lt;strong&gt;latent feature&lt;/strong&gt; is:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A property or concept that &lt;strong&gt;isn't explicitly observed&lt;/strong&gt; in the data, but is &lt;strong&gt;inferred&lt;/strong&gt; from patterns across the matrix.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In simple terms:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It's a &lt;strong&gt;hidden factor&lt;/strong&gt; that explains &lt;em&gt;why&lt;/em&gt; people behave the way they do.&lt;/li&gt;
&lt;li&gt;You &lt;strong&gt;don’t know what it is&lt;/strong&gt;, but you &lt;strong&gt;see its effects&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Analogy: Music Taste
&lt;/h4&gt;

&lt;p&gt;Imagine a user-song matrix: rows = users, columns = songs, entries = ratings.&lt;/p&gt;

&lt;p&gt;You don’t label features like "likes punk rock" or "prefers instrumental", but...&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If two users rate the same songs highly,&lt;/li&gt;
&lt;li&gt;And those songs share some &lt;em&gt;vibe&lt;/em&gt;,&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Then you can infer there's some &lt;strong&gt;latent preference&lt;/strong&gt; shared.&lt;br&gt;
That hidden dimension — like “preference for energetic music” — is a &lt;strong&gt;latent feature&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Definition
&lt;/h3&gt;

&lt;p&gt;Given any real matrix &lt;strong&gt;A&lt;/strong&gt; ∈ ℝ&lt;sup&gt;m×n&lt;/sup&gt;, SVD says:&lt;/p&gt;

&lt;p&gt;Where:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Component&lt;/th&gt;
&lt;th&gt;Shape&lt;/th&gt;
&lt;th&gt;Role&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;U&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;ℝ&lt;sup&gt;m×k&lt;/sup&gt;
&lt;/td&gt;
&lt;td&gt;Orthonormal matrix — maps original rows into a &lt;strong&gt;k-dimensional latent space&lt;/strong&gt;. Each row is a **latent [[Vectors\&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Σ&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;ℝ&lt;sup&gt;k×k&lt;/sup&gt;
&lt;/td&gt;
&lt;td&gt;Diagonal matrix with non-negative real numbers called &lt;strong&gt;singular values&lt;/strong&gt;, sorted from largest to smallest. These represent the &lt;strong&gt;importance (energy)&lt;/strong&gt; of each dimension in the latent space.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Vᵀ&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;ℝ&lt;sup&gt;k×n&lt;/sup&gt;
&lt;/td&gt;
&lt;td&gt;Orthonormal matrix — maps original columns into the same &lt;strong&gt;k-dimensional latent space&lt;/strong&gt;. Each column is a &lt;strong&gt;latent vector&lt;/strong&gt; for a column of A.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;The value &lt;strong&gt;k = rank(A)&lt;/strong&gt; in exact decomposition, or you can choose a smaller &lt;strong&gt;k&lt;/strong&gt; for approximation (low-rank SVD).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4&gt;
  
  
  📊 What Each Matrix Encodes (in abstract terms)
&lt;/h4&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Component&lt;/th&gt;
&lt;th&gt;Encodes&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;U&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Each row in A becomes a vector in a &lt;strong&gt;latent space&lt;/strong&gt; — capturing how each row projects onto abstract "directions" in the data.&lt;br&gt;&lt;br&gt;This matrix shows how &lt;strong&gt;each user&lt;/strong&gt; aligns with the &lt;strong&gt;latent features&lt;/strong&gt; discovered by SVD.&lt;br&gt;&lt;br&gt;It does &lt;strong&gt;not&lt;/strong&gt; label them explicitly as “loves punk rock” or “loves romantic music,” but it &lt;strong&gt;captures underlying preferences&lt;/strong&gt;.&lt;br&gt;&lt;br&gt;In essence, &lt;strong&gt;U&lt;/strong&gt; describes &lt;strong&gt;what kind of latent features (or preferences)&lt;/strong&gt; each user has, without explicitly telling us the names of those features. It just tells us the &lt;strong&gt;degree to which each user aligns with each latent feature&lt;/strong&gt;.&lt;br&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Σ&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Singular values show &lt;strong&gt;how much of A’s structure&lt;/strong&gt; lies in each direction (feature). The higher the value, the more "energy" or "information" it captures.&lt;br&gt;&lt;br&gt;The &lt;strong&gt;singular values&lt;/strong&gt; in &lt;strong&gt;Σ&lt;/strong&gt; represent how &lt;strong&gt;important&lt;/strong&gt; each latent feature is&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Vᵀ&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Each column in A becomes a vector in the same latent space — capturing how each column contributes along those same directions.&lt;br&gt;&lt;br&gt;This matrix describes how &lt;strong&gt;each song&lt;/strong&gt; correlates with the latent features.&lt;br&gt;&lt;br&gt;For example, &lt;br&gt;&lt;br&gt;&lt;strong&gt;Song A (Punk)&lt;/strong&gt; might have a high score for the latent feature "energetic music," &lt;br&gt;&lt;br&gt;while &lt;strong&gt;Song B (Romantic)&lt;/strong&gt; might also score highly on that feature, but could also have a moderate score for a latent feature related to "emotional depth" (which both romantic and punk music might share).&lt;br&gt;&lt;br&gt;&lt;strong&gt;Song C (Jazz)&lt;/strong&gt; and &lt;strong&gt;Song D (Classical)&lt;/strong&gt; would likely score higher on a latent feature related to "calm or soothing music."&lt;br&gt;&lt;br&gt;In essence, &lt;strong&gt;Vᵀ&lt;/strong&gt; describes &lt;strong&gt;what kind of latent features (or qualities)&lt;/strong&gt; each song has, again without explicitly telling us what the features are. It just tells us the &lt;strong&gt;degree to which each song aligns with each latent feature&lt;/strong&gt;.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h3&gt;
  
  
  Example Scenario
&lt;/h3&gt;

&lt;p&gt;Let’s start with a &lt;strong&gt;user-song rating matrix&lt;/strong&gt; where users rate songs from different genres. Each user has their own tastes, and some might enjoy music from different genres.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Song A (Punk)&lt;/th&gt;
&lt;th&gt;Song B (Romantic)&lt;/th&gt;
&lt;th&gt;Song C (Jazz)&lt;/th&gt;
&lt;th&gt;Song D (Classical)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Alice&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Bob&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Carol&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Alice&lt;/strong&gt;: Likes &lt;strong&gt;Song A (Punk)&lt;/strong&gt; and &lt;strong&gt;Song B (Romantic)&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Bob&lt;/strong&gt;: Likes &lt;strong&gt;Song B (Romantic)&lt;/strong&gt; and &lt;strong&gt;Song A (Punk)&lt;/strong&gt; as well, but with slightly different ratings.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Carol&lt;/strong&gt;: Prefers &lt;strong&gt;Song C (Jazz)&lt;/strong&gt; and &lt;strong&gt;Song D (Classical)&lt;/strong&gt;.
#### The Problem: How Do We Predict Missing Ratings?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We want to predict ratings for the &lt;strong&gt;missing entries&lt;/strong&gt; (denoted by &lt;code&gt;?&lt;/code&gt;). For example, we want to predict how Alice might rate &lt;strong&gt;Song C (Jazz)&lt;/strong&gt; or &lt;strong&gt;Song D (Classical)&lt;/strong&gt;. Similarly, we want to predict how Bob might rate &lt;strong&gt;Song C&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;We don't explicitly know which genres each user likes. But &lt;strong&gt;SVD&lt;/strong&gt; can discover &lt;strong&gt;latent features&lt;/strong&gt; or hidden preferences based on their ratings.&lt;/p&gt;

&lt;h4&gt;
  
  
  Breakdown of U, Σ, Vᵀ
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;U&lt;/strong&gt; (User-to-Latent Features) – Describes the users in terms of the latent features.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Σ&lt;/strong&gt; (Singular Values) – Indicates the importance of each latent feature.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Vᵀ&lt;/strong&gt; (Song-to-Latent Features) – Describes the songs in terms of the latent features.&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  U: &lt;strong&gt;User-to-Latent Feature Matrix&lt;/strong&gt;
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Rows (users)&lt;/strong&gt;: Each row in &lt;strong&gt;U&lt;/strong&gt; corresponds to one user.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Columns (latent features)&lt;/strong&gt;: Each column in &lt;strong&gt;U&lt;/strong&gt; corresponds to one latent feature that was discovered by SVD.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Values&lt;/strong&gt;: Each entry in &lt;strong&gt;U&lt;/strong&gt; shows how strongly a user aligns with each latent feature. A high value in a column indicates that the user has a strong preference for that particular latent feature. A low value means they don’t have much of a preference for that feature.&lt;/li&gt;
&lt;li&gt;Let’s say after applying SVD, we get a matrix &lt;strong&gt;U&lt;/strong&gt; for our music example that looks like this:&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Feature 1 (Energetic Music)&lt;/th&gt;
&lt;th&gt;Feature 2 (Calm Music)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Alice&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;0.8&lt;/td&gt;
&lt;td&gt;0.2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Bob&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;0.9&lt;/td&gt;
&lt;td&gt;0.1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Carol&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;-0.3&lt;/td&gt;
&lt;td&gt;0.9&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Alice&lt;/strong&gt; has a strong preference for &lt;strong&gt;Feature 1 (Energetic Music)&lt;/strong&gt; with a value of &lt;strong&gt;0.8&lt;/strong&gt;, and a weak preference for &lt;strong&gt;Feature 2 (Calm Music)&lt;/strong&gt; with a value of &lt;strong&gt;0.2&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Bob&lt;/strong&gt; also has a strong preference for &lt;strong&gt;Feature 1 (Energetic Music)&lt;/strong&gt; (0.9), but he has a much weaker preference for &lt;strong&gt;Feature 2 (Calm Music)&lt;/strong&gt; (0.1).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Carol&lt;/strong&gt;, on the other hand, has a strong preference for &lt;strong&gt;Feature 2 (Calm Music)&lt;/strong&gt; (0.9) and a weak preference for &lt;strong&gt;Feature 1 (Energetic Music)&lt;/strong&gt; (-0.3).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;What this Means:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Alice and Bob both like energetic music, which is why they have high values for &lt;strong&gt;Feature 1&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Carol prefers calm music, as indicated by her high value for &lt;strong&gt;Feature 2&lt;/strong&gt;.
#### Σ: &lt;strong&gt;Singular Value Matrix&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;A larger singular value indicates that the latent feature explains more of the variance in the ratings. For instance, the first latent feature might explain a significant portion of the ratings data (because both Alice and Bob like energetic music), while the second latent feature (which explains Carol’s preference for calm music) might explain less.&lt;/p&gt;

&lt;h4&gt;
  
  
  Vᵀ: &lt;strong&gt;Song-to-Latent Feature Matrix&lt;/strong&gt;
&lt;/h4&gt;


&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;strong&gt;Rows (songs)&lt;/strong&gt;: Each row in &lt;strong&gt;Vᵀ&lt;/strong&gt; corresponds to a particular song.&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;strong&gt;Columns (latent features)&lt;/strong&gt;: Each column corresponds to one latent feature discovered by SVD.&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;strong&gt;Values&lt;/strong&gt;: Each entry in &lt;strong&gt;Vᵀ&lt;/strong&gt; tells us how much the song aligns with a particular latent feature.&lt;/p&gt;&lt;/li&gt;

&lt;li&gt;&lt;p&gt;Here’s how the matrix &lt;strong&gt;Vᵀ&lt;/strong&gt; might look for our music example:&lt;/p&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Feature 1 (Energetic Music)&lt;/th&gt;
&lt;th&gt;Feature 2 (Calm Music)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Song A (Punk)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;0.9&lt;/td&gt;
&lt;td&gt;-0.1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Song B (Romantic)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;0.8&lt;/td&gt;
&lt;td&gt;0.2&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Song C (Jazz)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;-0.2&lt;/td&gt;
&lt;td&gt;0.9&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Song D (Classical)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;-0.5&lt;/td&gt;
&lt;td&gt;0.8&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Song A (Punk)&lt;/strong&gt; has a high value for &lt;strong&gt;Feature 1 (Energetic Music)&lt;/strong&gt; (0.9), meaning that this song aligns with energetic or lively music, but it has a low value for &lt;strong&gt;Feature 2 (Calm Music)&lt;/strong&gt; (-0.1), meaning it doesn't align with calm or soothing music.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Song B (Romantic)&lt;/strong&gt; also has a high value for &lt;strong&gt;Feature 1 (Energetic Music)&lt;/strong&gt; (0.8) but also has a moderate value for &lt;strong&gt;Feature 2 (Calm Music)&lt;/strong&gt; (0.2), showing it may combine both energetic and calming elements.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Song C (Jazz)&lt;/strong&gt; has a low value for &lt;strong&gt;Feature 1 (Energetic Music)&lt;/strong&gt; (-0.2) and a high value for &lt;strong&gt;Feature 2 (Calm Music)&lt;/strong&gt; (0.9), meaning it's a calm, soothing song.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Song D (Classical)&lt;/strong&gt; also has a low value for &lt;strong&gt;Feature 1 (Energetic Music)&lt;/strong&gt; (-0.5) and a high value for &lt;strong&gt;Feature 2 (Calm Music)&lt;/strong&gt; (0.8), making it more of a calm or soothing piece of music.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;What this Means:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Vᵀ&lt;/strong&gt; shows us how &lt;strong&gt;each song relates to the latent features&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Song A (Punk)&lt;/strong&gt; is closely related to &lt;strong&gt;Feature 1 (Energetic Music)&lt;/strong&gt;, while &lt;strong&gt;Song C (Jazz)&lt;/strong&gt; is closely related to &lt;strong&gt;Feature 2 (Calm Music)&lt;/strong&gt;.
### Key Insight: What SVD Actually Reveals&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;Here’s where &lt;strong&gt;SVD’s magic&lt;/strong&gt; comes in:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;strong&gt;Alice and Bob&lt;/strong&gt; like both &lt;strong&gt;Song A (Punk)&lt;/strong&gt; and &lt;strong&gt;Song B (Romantic)&lt;/strong&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;SVD captures that they share a preference for energetic, lively music&lt;/strong&gt;, even though one song is punk and the other is romantic.&lt;/li&gt;
&lt;li&gt;This shared preference shows up as a &lt;strong&gt;latent feature&lt;/strong&gt; in &lt;strong&gt;U&lt;/strong&gt; for Alice and Bob: both have high scores for this feature.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;&lt;strong&gt;Carol&lt;/strong&gt;, on the other hand, likes &lt;strong&gt;Song C (Jazz)&lt;/strong&gt; and &lt;strong&gt;Song D (Classical)&lt;/strong&gt;, which are more calm and soothing.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;SVD identifies this preference&lt;/strong&gt; as another &lt;strong&gt;latent feature&lt;/strong&gt;, and Carol scores highly on this second latent feature in &lt;strong&gt;U&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;&lt;strong&gt;SVD doesn’t explicitly label these features as genres&lt;/strong&gt; like “punk” or “romantic.”&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It simply sees that &lt;strong&gt;Alice and Bob&lt;/strong&gt; share some ratings for energetic music, and &lt;strong&gt;Carol&lt;/strong&gt; shares ratings for calming music.&lt;/li&gt;
&lt;li&gt;This means SVD will identify &lt;strong&gt;latent features&lt;/strong&gt; that explain why Alice and Bob like &lt;strong&gt;Songs A and B&lt;/strong&gt;, and why Carol prefers &lt;strong&gt;Songs C and D&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;h4&gt;
  
  
  Predicting Missing Ratings with SVD
&lt;/h4&gt;

&lt;p&gt;Now that we understand what each matrix represents, let's see how SVD helps us predict missing ratings:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We've decomposed our original ratings matrix into U, Σ, and Vᵀ&lt;/li&gt;
&lt;li&gt;To predict Alice's rating for Song C (Jazz), we multiply her latent feature values by the importance of each feature, then by Song C's latent feature values:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Alice's predicted rating for Song C = (U_Alice × Σ × Vᵀ_SongC)&lt;/p&gt;

&lt;p&gt;Using our example values:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Alice's latent feature values: [0.8, 0.2]&lt;/li&gt;
&lt;li&gt;Singular values (assuming Σ = [[3, 0], [0, 2]]): 3 for Feature 1, 2 for Feature 2&lt;/li&gt;
&lt;li&gt;Song C's latent feature values: [-0.2, 0.9]&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Calculation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Alice's preference for Feature 1 × Importance of Feature 1 × Song C's alignment with Feature 1:&lt;br&gt;
0.8 × 3 × (-0.2) = -0.48&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Alice's preference for Feature 2 × Importance of Feature 2 × Song C's alignment with Feature 2:&lt;br&gt;
0.2 × 2 × 0.9 = 0.36&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Sum these values: -0.48 + 0.36 = -0.12&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Since ratings are typically positive, we might scale this to a rating range (e.g., 1-5):&lt;br&gt;
Adjusted rating ≈ 2.5 (neutral/slightly negative)&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This makes intuitive sense: Alice strongly prefers energetic music (Feature 1), but Song C (Jazz) is negatively associated with that feature and strongly associated with calm music (Feature 2), which Alice only weakly prefers. Therefore, SVD predicts Alice would give Song C a relatively low rating.&lt;/p&gt;

&lt;h3&gt;
  
  
  Application in Dimensionality Reduction
&lt;/h3&gt;

&lt;p&gt;In real-world data, there’s often a lot of &lt;strong&gt;redundancy&lt;/strong&gt; — users rate songs similarly, or products have overlapping qualities. SVD helps by:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Capturing the most important features (patterns)&lt;/strong&gt; in the data.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Removing noise and redundancy&lt;/strong&gt; by ignoring less significant singular values.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Compressing the data&lt;/strong&gt;: Instead of storing the full original matrix, we store a low-rank approximation.&lt;/li&gt;
&lt;/ul&gt;




&lt;h4&gt;
  
  
  How the Reduction Works
&lt;/h4&gt;

&lt;p&gt;To reduce dimensionality:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Choose a smaller rank &lt;code&gt;k&lt;/code&gt;&lt;/strong&gt;, where &lt;code&gt;k &amp;lt; full rank&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Keep only the top &lt;code&gt;k&lt;/code&gt; singular values and their corresponding vectors in &lt;code&gt;U&lt;/code&gt; and &lt;code&gt;Vᵀ&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Reconstruct the matrix approximately:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;$A_k \approx U_k \Sigma_k V_k^T$&lt;/p&gt;

&lt;p&gt;This &lt;strong&gt;reduced version&lt;/strong&gt; of the matrix retains most of the meaningful information but uses far fewer numbers.&lt;/p&gt;




&lt;h4&gt;
  
  
  👥 Example: Alice, Bob, and Carol
&lt;/h4&gt;

&lt;p&gt;Imagine we have a matrix of 3 users (Alice, Bob, Carol) rating 4 songs:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;&lt;/th&gt;
&lt;th&gt;Punk&lt;/th&gt;
&lt;th&gt;Rock&lt;/th&gt;
&lt;th&gt;Love&lt;/th&gt;
&lt;th&gt;Ballad&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Alice&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Bob&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Carol&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;5&lt;/td&gt;
&lt;td&gt;4&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;This is a &lt;strong&gt;3×4&lt;/strong&gt; matrix.&lt;/p&gt;

&lt;p&gt;After applying SVD and reducing it to &lt;strong&gt;k = 2&lt;/strong&gt;, we get:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;U_k&lt;/code&gt;: 3×2 matrix — Each user represented by just 2 latent features.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Σ_k&lt;/code&gt;: 2×2 diagonal matrix — Strength of these 2 features.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;V_kᵀ&lt;/code&gt;: 2×4 matrix — Each song represented using just 2 features.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This reduced version:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Reveals that Alice and Bob prefer a “Punk/Rock” dimension, while Carol prefers a “Love/Ballad” dimension.&lt;/li&gt;
&lt;li&gt;Allows us to &lt;strong&gt;reconstruct an approximation&lt;/strong&gt; of the original matrix using just the most important patterns.&lt;/li&gt;
&lt;li&gt;Reduces noise and dimensionality without losing much of the core structure.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Why to perform this?
&lt;/h4&gt;

&lt;h5&gt;
  
  
  1. &lt;strong&gt;Captures Core Patterns, Not Raw Values&lt;/strong&gt;
&lt;/h5&gt;

&lt;p&gt;The original matrix told you explicitly:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;“Alice rated Punk 5, Love 1…”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;But those are &lt;em&gt;surface-level&lt;/em&gt; observations.&lt;br&gt;&lt;br&gt;
The reduced version asks:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;“What underlying factors might explain why Alice likes Punk and Rock more?”&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Maybe &lt;strong&gt;Factor 1&lt;/strong&gt; represents a preference for &lt;em&gt;high-energy music&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;Maybe &lt;strong&gt;Factor 2&lt;/strong&gt; represents a preference for &lt;em&gt;emotional or romantic themes&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the reduced matrix, Alice might be represented as:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Alice → [2.1, 0.1] → Strong on Factor 1, Weak on Factor 2 Carol → [0.1, 2.3] → Weak on Factor 1, Strong on Factor 2&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This tells us more than raw numbers — it shows &lt;strong&gt;why&lt;/strong&gt; people like what they like.&lt;/p&gt;




&lt;h4&gt;
  
  
  2. &lt;strong&gt;Good Generalization — Not Just Memorization&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;The full matrix memorizes exact numbers.&lt;br&gt;&lt;br&gt;
The reduced matrix &lt;strong&gt;generalizes&lt;/strong&gt;, letting us:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Predict missing values more robustly.&lt;/li&gt;
&lt;li&gt;Spot similar users or items even if their ratings don’t match exactly.&lt;/li&gt;
&lt;li&gt;Cluster users or songs by deeper, shared preferences.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is crucial in recommendation systems like Netflix or Spotify — we often have &lt;strong&gt;incomplete data&lt;/strong&gt;, and we want &lt;strong&gt;smart predictions&lt;/strong&gt;, not perfect reconstructions.&lt;/p&gt;




&lt;h4&gt;
  
  
  3. &lt;strong&gt;Removes Noise&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;In real-world data, some ratings are noisy:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A person misclicked a 1 instead of 4.&lt;/li&gt;
&lt;li&gt;Someone rated a song randomly.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;SVD smooths over such inconsistencies by &lt;strong&gt;focusing on consistent trends&lt;/strong&gt;, not one-off values.&lt;/p&gt;




&lt;h3&gt;
  
  
  Conclusion: Why SVD Matters
&lt;/h3&gt;

&lt;p&gt;SVD's power lies in its ability to:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Discover hidden patterns (latent features) in data&lt;/li&gt;
&lt;li&gt;Reduce dimensionality while preserving important information&lt;/li&gt;
&lt;li&gt;Enable accurate predictions for missing values&lt;/li&gt;
&lt;li&gt;Filter noise from data&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Whether you're building recommendation systems, processing images, or analyzing text, SVD provides a mathematical foundation for understanding and working with complex data relationships.&lt;/p&gt;




</description>
    </item>
    <item>
      <title>Error-Correcting Codes: Hamming Code</title>
      <dc:creator>Samyak Jain</dc:creator>
      <pubDate>Mon, 03 Mar 2025 12:11:09 +0000</pubDate>
      <link>https://dev.to/samyak112/error-correcting-codes-hamming-code-2pip</link>
      <guid>https://dev.to/samyak112/error-correcting-codes-hamming-code-2pip</guid>
      <description>&lt;p&gt;So recently I started to read about error detection, that how error detection started and implemented, &lt;/p&gt;

&lt;p&gt;But wait—what kind of errors are we dealing with? Lets take an example of ECC RAM (Error-Correcting Code RAM). Unlike the RAM in your laptop, which can afford the occasional unnoticed error, ECC RAM actively fixes mistakes in real-time—because in places like banks and space missions, even a single corrupted bit could mean disaster.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lets take an example&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let’s say a server is storing &lt;strong&gt;financial transactions&lt;/strong&gt; in RAM.  You might think errors happen due to faulty hardware or software bugs and it should be fixable normally, whats the big deal? &lt;br&gt;
But sometimes, errors don’t come from faulty code or bad hardware—they come from  something you cant control like outer space!!  A random bit flip occurs due to cosmic radiation.&lt;/p&gt;

&lt;p&gt;Cosmic rays are &lt;strong&gt;high-energy particles from space&lt;/strong&gt; (mainly protons) that constantly hit Earth. When they strike electronic components, they can knock electrons loose, &lt;strong&gt;causing bit flips in memory&lt;/strong&gt;. This is called a &lt;strong&gt;Single Event Upset (SEU)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;So due to cosmic radiation the stored amount &lt;strong&gt;$1000&lt;/strong&gt; (binary &lt;code&gt;1111101000&lt;/code&gt;) accidentally becomes &lt;strong&gt;$1008&lt;/strong&gt; (binary &lt;code&gt;1111101100&lt;/code&gt;). Just a single bit got flipped and hence it changed the amount saved in the system. That’s a serious problem—imagine this happening thousands of times across a banking system.&lt;/p&gt;
&lt;h3&gt;
  
  
  A bit of history..
&lt;/h3&gt;

&lt;p&gt;So in 1940s there was an American mathematician and Engineer &lt;strong&gt;Richard Hamming&lt;/strong&gt; who was working at Bell Labs and used to access a complex punch card computer, and the programs that he used to pass through kept failing because of the random error which used to flip a bit and the whole program used to crash.&lt;/p&gt;

&lt;p&gt;Frustrated by unintentional errors caused by factors beyond human control (like cosmic radiation), he developed the first error correction code.&lt;/p&gt;
&lt;h3&gt;
  
  
  Parity Checks
&lt;/h3&gt;

&lt;p&gt;Before talking about hamming's algorithm there is some context we need to have about parity checks, because its used heavily in Hamming's algorithm. The idea of Parity checks is pretty simple but cool. To understand Parity Checks lets take an example&lt;/p&gt;

&lt;p&gt;Let’s say we need to transmit a &lt;strong&gt;7-bit message&lt;/strong&gt;, and its binary representation looks like this: - &lt;code&gt;1101010&lt;/code&gt; , now, when the receiver gets this message, how do they know whether it was transmitted correctly or if an error occurred?&lt;/p&gt;

&lt;p&gt;To help with this, a &lt;strong&gt;parity bit&lt;/strong&gt; is added to the message. Instead of sending just 7 bits, we send &lt;strong&gt;8 bits&lt;/strong&gt;, where &lt;strong&gt;one extra bit&lt;/strong&gt; is included purely for error detection.&lt;/p&gt;
&lt;h4&gt;
  
  
  &lt;strong&gt;Even Parity Check&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;One common method is the &lt;strong&gt;even parity check&lt;/strong&gt;, where:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We count the number of &lt;code&gt;1s&lt;/code&gt; in the message.&lt;/li&gt;
&lt;li&gt;If the number of &lt;code&gt;1s&lt;/code&gt; is &lt;strong&gt;odd&lt;/strong&gt;, we add a &lt;code&gt;1&lt;/code&gt; as the parity bit to make the total count &lt;strong&gt;even&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;If the number of &lt;code&gt;1s&lt;/code&gt; is already &lt;strong&gt;even&lt;/strong&gt;, we add a &lt;code&gt;0&lt;/code&gt; as the parity bit to keep it even.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For example, in our message &lt;code&gt;1101010&lt;/code&gt;, the number of &lt;code&gt;1s&lt;/code&gt; is &lt;strong&gt;four&lt;/strong&gt; (which is already even). So, the parity bit added will be &lt;code&gt;0&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Original message:  1101010  
Parity bit:        0  
Transmitted data:  11010100  

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If instead the message was &lt;code&gt;1101011&lt;/code&gt; (which has &lt;strong&gt;five&lt;/strong&gt; &lt;code&gt;1s&lt;/code&gt;), we would add a &lt;code&gt;1&lt;/code&gt; to make it even:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Original message:  1101011  
Parity bit:        1  
Transmitted data:  11010111  

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  &lt;strong&gt;Error Detection with Parity Checks&lt;/strong&gt;
&lt;/h4&gt;

&lt;p&gt;After transmission, the receiver &lt;strong&gt;recounts&lt;/strong&gt; the number of &lt;code&gt;1s&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If the total count is &lt;strong&gt;even&lt;/strong&gt;, the message is considered &lt;strong&gt;correct&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;If the total count is &lt;strong&gt;odd&lt;/strong&gt;, it means &lt;strong&gt;an error occurred&lt;/strong&gt; during transmission.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Parity checks are a simple and efficient way to &lt;strong&gt;detect&lt;/strong&gt; errors.&lt;/p&gt;

&lt;h4&gt;
  
  
  Problem in Parity Checks
&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;1. False Positives&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A parity bit works by ensuring that the total number of &lt;strong&gt;1s in a message (including the parity bit) is always even (or odd, depending on the scheme).&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If a &lt;strong&gt;single&lt;/strong&gt; bit flips due to an error, the parity check will detect it because the total count of 1s will become incorrect.&lt;/li&gt;
&lt;li&gt;But if &lt;strong&gt;two bits flip&lt;/strong&gt;, the total count of 1s changes by &lt;strong&gt;+2 or -2&lt;/strong&gt;, which still maintains the even (or odd) parity, making the error &lt;strong&gt;undetectable&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example of Two-Bit Error Failure&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Suppose we use &lt;strong&gt;even parity&lt;/strong&gt; and transmit this 8-bit data with a parity bit:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Data&lt;/th&gt;
&lt;th&gt;Parity Bit&lt;/th&gt;
&lt;th&gt;Total 1s (should be even)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;10110010&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;4 (even)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;If a single-bit error occurs (e.g., &lt;strong&gt;101100&lt;/strong&gt;1*&lt;em&gt;0 → 101100&lt;/em&gt;&lt;em&gt;0&lt;/em&gt;&lt;em&gt;0&lt;/em&gt;&lt;em&gt;), the number of 1s changes from **4 → 3&lt;/em&gt;*, which is odd, and the error is detected.&lt;/p&gt;

&lt;p&gt;But if &lt;strong&gt;two bits flip&lt;/strong&gt; (e.g., &lt;strong&gt;10110010 → 11110000&lt;/strong&gt;), the number of 1s changes from &lt;strong&gt;4 → 4&lt;/strong&gt; (still even), and the error is &lt;strong&gt;not detected&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. No way to pinpoint the error&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Although we could detect the presence of an error, we had no way of identifying &lt;em&gt;which&lt;/em&gt; bit was incorrect. The only solution was to retransmit the entire message—a costly and inefficient approach.&lt;/p&gt;

&lt;h3&gt;
  
  
  Hamming Codes
&lt;/h3&gt;

&lt;p&gt;So when Richard hamming was facing this issue in his Punch Card computer, he created an algorithm which is today known as Hamming Codes.&lt;/p&gt;

&lt;p&gt;Now Hamming's Algorithm also uses parity checks but instead of using just one parity bit for the entire message, he introduced multiple parity bits. Their positions are strategically calculated based on binary representation, allowing errors to be not only &lt;strong&gt;detected&lt;/strong&gt; but also &lt;strong&gt;corrected&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Before getting into details lets just abstract everything , we will use multiple parity bits to help us identify and fix errors. Although their positions follow a specific calculation, for now, I’ll place them manually and explain the logic behind their placement later.&lt;/p&gt;

&lt;p&gt;For this example, we will use a 7-bit message with 4 parity bits along with 1 extra bit (which we’ll ignore for now). This gives us the following structure, like this..&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F584b1vw6o69c4d7euiwm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F584b1vw6o69c4d7euiwm.png" alt="Image description" width="800" height="829"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;See the 4 highlighted cells? Those are our parity bits , we’ll discuss how their positions were determined later, but for now, let's focus on how we use them to detect errors.&lt;/p&gt;

&lt;p&gt;So How do we use these 4 parity bits now? The process is similar to a simple parity check, but instead of a single parity bit verifying the entire message, each parity bit is responsible for checking a specific subset of bits.&lt;br&gt;
(How are these subsets assigned? We’ll cover that soon.)&lt;/p&gt;

&lt;p&gt;Lets take this set first&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpiqclnj4ba54ztv26h5m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpiqclnj4ba54ztv26h5m.png" alt="Image description" width="800" height="829"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Parity at index 1&lt;/strong&gt;&lt;br&gt;
Here, the parity bit is at index 1, and its corresponding set of message bits is highlighted.&lt;/p&gt;

&lt;p&gt;Running a standard parity check, we see that the number of 1s is even, meaning this subset is correct—no error detected.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Parity at index 2&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Next, we move to the parity bit at index 2: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F32hfw5yk901bjpcpdbul.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F32hfw5yk901bjpcpdbul.png" alt="Image description" width="800" height="829"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Checking parity here, we find an odd number of 1s, which indicates an error in one of these bits—but we don’t know which one yet.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Parity at index 4&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frf3o56wp8kteqngnqss4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frf3o56wp8kteqngnqss4.png" alt="Image description" width="800" height="822"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, let’s check the index 4 parity bit, covering the 2nd and 4th rows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
The parity check here is even, meaning no errors were found in this subset.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;4. Parity at index 8&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbr6ylfb16dtm4f2h93do.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbr6ylfb16dtm4f2h93do.png" alt="Image description" width="800" height="822"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The last parity bit, at index 8, covers the 3rd and 4th rows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
Running a parity check, we find an odd number of 1s, confirming an error in this subset as well.
Pinpointing the Error&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;Parity bit at index 1 verified that column 2 is correct.&lt;/li&gt;
&lt;li&gt;Parity bit at index 2 revealed an error in either column 1 or column 3.&lt;/li&gt;
&lt;li&gt;Parity bit at index 4 confirmed that the error is not in column 2, narrowing it down further.&lt;/li&gt;
&lt;li&gt;Parity bit at index 8 confirmed the error is in index 10.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;By combining these results, we precisely locate the error bit and can correct it.&lt;/p&gt;

&lt;p&gt;Haha, sounds like just luck, right? I mean, what if the error was one bit higher or lower? These errors happen randomly, so how can we be sure this ‘intersection’ always works? Are we just hoping for the best? So many questions!!!&lt;/p&gt;

&lt;p&gt;Actually this above example was just to give an idea that how the algorithm works at an uber level, so that when i go in the actual intuition behind each step i can refer to the above example.&lt;/p&gt;

&lt;h4&gt;
  
  
  Parity Bit Placement Logic
&lt;/h4&gt;

&lt;p&gt;Ok , so the parity bit's locations are not just selected randomly but are based on the property of &lt;a href="https://courses.cs.vt.edu/cs2505/fall2012/Notes/T13_NumericBases.pdf" rel="noopener noreferrer"&gt;Positional Notation&lt;/a&gt; (a &lt;strong&gt;numerical representation system&lt;/strong&gt; where the value of a digit depends on its &lt;strong&gt;position&lt;/strong&gt; in the number.)&lt;/p&gt;

&lt;p&gt;In any positional notation system, a number is either:  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A &lt;strong&gt;single power&lt;/strong&gt; of the base (if it corresponds to a pure power).
&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;sum of multiple distinct powers&lt;/strong&gt; of the base (if it is not a pure power).
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For Example&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Binary (Base 2)&lt;/strong&gt;  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;8&lt;/strong&gt; → &lt;code&gt;1000&lt;/code&gt; → ( 2^3 ) (a single power of 2)
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;10&lt;/strong&gt; → &lt;code&gt;1010&lt;/code&gt; → ( 2^3 + 2^1 ) (sum of distinct powers of 2)
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Decimal (Base 10)&lt;/strong&gt;  &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;1000&lt;/strong&gt; → ( 10^3 ) (a single power of 10)
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;1,234&lt;/strong&gt; → ( 10^3 + 2 \times 10^2 + 3 \times 10^1 + 4 \times 10^0 ) (sum of distinct powers of 10) &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;But how did Hamming used this property?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The whole logic doesn’t rely on the values of the bits but on their positions. Hamming placed the parity bits at positions that are pure powers of 2 (i.e., 1, 2, 4, 8, …). These positions are chosen because their binary representation contains only a single 1, meaning they are not formed by summing multiple powers of 2.&lt;/p&gt;

&lt;p&gt;But why choose only pure powers? Because every other number is just a combination of two or more pure powers of 2. For example, 9 is formed by 2³ + 2⁰, which in binary is 1001.&lt;/p&gt;

&lt;p&gt;By reserving these pure power positions for parity bits, we can systematically group all other bits under the relevant parity checks. Any bit whose binary representation has 1 in the least significant position (i.e., xxxx1) falls under parity bit at index 1 (0001), meaning it contributes to the 2⁰ position.&lt;/p&gt;

&lt;p&gt;However, bits do not belong to just one parity check. Since numbers are made up of multiple powers of 2, a bit like 9 (1001) falls under both parity bit at index 8 (2³) and parity bit at index 1 (2⁰).&lt;/p&gt;

&lt;p&gt;So now, if you look at the grid above, the example images I added—and the specific set of bits assigned to each parity bit—should start to make sense. Each parity bit is responsible for checking all positions that include its corresponding power of 2 in their binary representation. This systematic assignment is what actually allows us to detect and correct errors efficiently.&lt;/p&gt;

&lt;p&gt;At first I was a bit confused that are we sure that each number will be uniquely covered? I mean can't the combination of two parity bits point at two different message bits? &lt;/p&gt;

&lt;p&gt;Well first of all thats not mathematically possible that exactly n pure base 2 powers will result in two different numbers i mean thats not mathematically possible.&lt;/p&gt;

&lt;p&gt;When performing parity checks on all blocks, I can identify that errors exist in specific parity blocks (e.g., X and Y). When I XOR these parity bits, I pinpoint the exact erroneous bit.&lt;/p&gt;

&lt;p&gt;Why? Because parity bits are derived from power-of-2 structures, meaning each parity bit corresponds to a unique set of data bits. The sum (or XOR) of two such independent parity bits always resolves to a single, unique bit position.&lt;/p&gt;

&lt;p&gt;Mathematically, since each parity bit represents a distinct power-of-2 contribution, their combination can only result in a single nonzero bit—which directly identifies the erroneous bit. This follows from the fundamental property that the XOR of two distinct power-of-2 values always results in a unique power-of-2 value, which corresponds to a specific bit position.&lt;/p&gt;

&lt;p&gt;But just for reference here is a table.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Position&lt;/th&gt;
&lt;th&gt;Binary&lt;/th&gt;
&lt;th&gt;P1 (1)&lt;/th&gt;
&lt;th&gt;P2 (2)&lt;/th&gt;
&lt;th&gt;P3 (4)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;1 (P1)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;001&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;2 (P2)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;010&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;3 (D1)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;011&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;4 (P3)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;100&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;5 (D2)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;101&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;6 (D3)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;110&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;❌&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;7 (D4)&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;strong&gt;111&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;td&gt;✅&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Ok so if you remember now that our Index 2 and Index 8 Parity bit failed right? So how do we pinpoint the exact error bit in a more robust or mathematical way? Instead of that kind of a luck intersection way?&lt;/p&gt;

&lt;p&gt;Well One way is to do XOR operation on the final failed parity bits which in our case are &lt;strong&gt;P2 and P8&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now, XOR their positions:&lt;/p&gt;

&lt;p&gt;2 (₁₀) = 0010₂&lt;br&gt;
8 (₁₀) = 1000₂&lt;br&gt;
XOR: 0010₂ ⊕ 1000₂ = 1010₂ = 10 (₁₀)&lt;/p&gt;

&lt;p&gt;This tells us that the bit at index 10 was flipped please flip it again.&lt;/p&gt;

&lt;p&gt;This way using Hamming code we not only found that there was an error bit but also Fixed it.&lt;/p&gt;

&lt;h4&gt;
  
  
  Calculating the Parity Bit
&lt;/h4&gt;

&lt;p&gt;Ok , we discussed the importance and maths behind the placement of the Parity bit , but what about the value of the Parity bit? Well its same as the normal Parity bit calcualtion, if in a specific set the number of 1s are even then the parity bit will be 0 otherwise 1.&lt;/p&gt;

&lt;h3&gt;
  
  
  Two Error Bit Detection (Extended Hamming Codes)
&lt;/h3&gt;

&lt;p&gt;Now that was all about detecting and correcting a single bit , but with Hamming's algorithm we can also detect (not fix) but detect if there was one more error or not.&lt;/p&gt;

&lt;p&gt;Remember the bit at index 0 that we ignored earlier? That bit is used for additional error detection. After correcting the first detected error, we check the bit at index 0 to see if the total number of 1s in the message is even. If it's still odd, that means there's another error somewhere in the message.&lt;/p&gt;

&lt;h3&gt;
  
  
  Increase in Parity bits with increase in Message bits.
&lt;/h3&gt;

&lt;p&gt;It might feel concerning that how many parity bits will we need to add as the size of the message increases. Well its really negligible just to give you an idea of scale for a 256 bit message the number of parity bits used are &lt;code&gt;9&lt;/code&gt; and I think thats reasonable.&lt;/p&gt;

&lt;p&gt;The number of parity bits ( P ) required for a message of ( D ) data bits in Hamming Code follows the formula:&lt;/p&gt;

&lt;p&gt;2&lt;sup&gt;p&lt;/sup&gt; ≥  𝐷 + p + 1&lt;/p&gt;

&lt;p&gt;where:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;( P ) = number of parity bits&lt;/li&gt;
&lt;li&gt;( D ) = number of data bits&lt;/li&gt;
&lt;li&gt;The extra ( +1 ) accounts for the overall code length (data + parity).&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Rationale behind this..
&lt;/h4&gt;

&lt;p&gt;To detect and correct single-bit errors, each bit position must have a unique binary representation using the parity bits.&lt;/p&gt;

&lt;p&gt;We have D data bits and P parity bits, so the total number of bits is D + P.&lt;br&gt;
We need to identify errors in any of these D + P bits plus one extra case (no error).&lt;br&gt;
This means we need at least D + P + 1 unique error states.&lt;/p&gt;

&lt;p&gt;Since each parity bit combination forms a binary number, the total number of unique error states that can be represented by P parity bits is:&lt;/p&gt;

&lt;p&gt;2&lt;sup&gt;p&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;Thus, to ensure that we can represent all possible error positions (including the "no error" case), we need:&lt;/p&gt;

&lt;p&gt;2&lt;sup&gt;p&lt;/sup&gt; ≥ 𝐷 + p + 1&lt;/p&gt;

&lt;p&gt;This blog is heavily inspired by &lt;a href="https://www.youtube.com/watch?v=X8jsijhllIA" rel="noopener noreferrer"&gt;3Blue1Brown’s excellent video&lt;/a&gt;. I highly recommend checking it out!&lt;/p&gt;

&lt;p&gt;If you spot any mistakes or feel that something could be explained better, let me know—I’ll make sure to correct it.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>learning</category>
      <category>architecture</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>Ref in React : Remote access to DOM elements</title>
      <dc:creator>Samyak Jain</dc:creator>
      <pubDate>Tue, 09 Apr 2024 11:02:55 +0000</pubDate>
      <link>https://dev.to/samyak112/refs-remote-access-to-elements-74f</link>
      <guid>https://dev.to/samyak112/refs-remote-access-to-elements-74f</guid>
      <description>&lt;p&gt;Ever struggled with making two unrelated components in React interact smoothly without cluttering your code? You're not alone. Let's explore a clean, efficient solution&lt;/p&gt;

&lt;p&gt;Let's say you created a file input element and clicking on it does your work but then you also have a button which when clicked on, you want the same functionality. But don't want to wrap the button in the input tag as well because it's already defined. You may need to focus on a node, scroll to it, or measure its size and position.&lt;/p&gt;

&lt;p&gt;Many of you must be familiar with these use cases from vanilla JS, where it provides functions like getElementByID and you do same things like these and you can surely use the same in React as well.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;BUT&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It is not recommended to mix vanilla JavaScript DOM manipulation methods like getElementById with React applications. This is because React manages the DOM differently through its virtual DOM and reconciliation process.&lt;/p&gt;

&lt;p&gt;React's declarative approach encourages managing the DOM through state and props and updating the UI in response to changes in state. &lt;/p&gt;

&lt;p&gt;Directly manipulating the DOM using methods like getElementById can lead to inconsistencies between the virtual DOM managed by React and the actual DOM, potentially causing unexpected behavior and bugs in your application.&lt;/p&gt;

&lt;p&gt;That's where the Refs comes into the picture in React. I think of refs as a way to remotely access an element from another element, even when the other element is not related to the first element in any way.&lt;/p&gt;

&lt;p&gt;If I had to give an analogy of refs, Refs are like a way to turn your fan ON through your mobile phone when traditionally you can do that only through the button which is connected to the fan.&lt;/p&gt;

&lt;p&gt;It provides us a way to interact with elements and store their information, I can add a ref attribute on a div and store its reference in a useRef hook and then call it in the onClick listener of another div, which is not related to the previous div in any way.&lt;/p&gt;

&lt;p&gt;Here is a &lt;a href="https://codesandbox.io/p/sandbox/simplerefexample-kmrhfs?file=%2Fsrc%2FApp.js%3A2%2C17" rel="noopener noreferrer"&gt;sandbox link&lt;/a&gt; where I used a useRef to trigger a file Input field through a button.&lt;/p&gt;

&lt;p&gt;You’ll see that when you select a file either with the input button or the custom button, you’ll see the message ‘I got called’ when you select a file because we are just accessing the reference of the original input field through the custom button.&lt;/p&gt;

&lt;p&gt;But why should I use only useRef for this purpose? Why I shouldn't use a useState for this? I mean we are just storing the reference of an element right? &lt;/p&gt;

&lt;p&gt;Well, the main reason is simply that useState is not designed for this use case, State (useState) is used for data that, when changed, should re-render the component. State is reactive; changes to state variables trigger component re-renders.&lt;/p&gt;

&lt;p&gt;State is intended for data that, when changed, should update the UI. However, a DOM element reference (like an input field) doesn't inherently require UI updates when set.&lt;/p&gt;

&lt;p&gt;Each time the ref changes (which can be often, due to the nature of inline function refs), it causes a state update and thus a re-render of the component. This is inefficient and unnecessary for simply referencing a DOM element.&lt;/p&gt;

&lt;p&gt;Thats why useRef is the better option here because making any change in the useRef-based variable does not cause a re-render.&lt;/p&gt;

&lt;p&gt;Ok, so we get it that it's against React’s design principles to use useState for this purpose, but still if I totally neglect this reasoning and still decide to use useState for storing reference, what harm can it cause to the basic working of my feature?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Delay in Availability&lt;/strong&gt;&lt;br&gt;
State updates in React are asynchronous. When you update a state with a new DOM reference, there's a brief period before the state is actually updated. This can lead to timing issues where you try to access the ref before the state has updated, potentially leading to errors or undefined values.&lt;/p&gt;

&lt;p&gt;Here is a &lt;a href="https://codesandbox.io/p/sandbox/usestatevsuserefexample-lhjqkf?file=%2Fsrc%2FApp.js%3A28%2C6" rel="noopener noreferrer"&gt;sandbox link&lt;/a&gt; which demonstrates using ref with useState and useRef and explains why you should use useRef for storing references instead of useState.&lt;/p&gt;

&lt;p&gt;Now if you checked the working example, you can see that The inputRef might not be immediately available after setting due to React's asynchronous state updates. This could lead to timing issues or undefined values when trying to access or interact with the input element right after it's mounted.&lt;/p&gt;

&lt;p&gt;Ref attribute looks cool, right? But over usage of this ref attribute and using it for everything is again a bad idea, just like useState didn’t fit in ref’s use case same way ref doesn't fits every where else as well.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;So when to use Ref generally?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When you need direct access to a DOM element to perform actions that cannot be done declaratively through React's state system, ref is the tool to use. Common use cases include:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Focusing an Input&lt;/strong&gt; - Programmatically setting focus on an input field when a component mounts or in response to specific user interactions.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Measuring Elements&lt;/strong&gt; - Obtaining measurements (e.g., width, height, or position) of an element that are only available via the DOM API.&lt;/li&gt;
&lt;li&gt;Managing Focus, Text Selection, or Media Control ref allows you to manage focus, select text, or control media playback (play, pause, seek) in a way that is not possible through declarative state updates alone.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now these examples are just some examples which were top of my mind, there can be a lot of creative ways to use ref attribute.&lt;/p&gt;

&lt;p&gt;Now that we have understood about refs, their use cases, and all the other considerations, let's see how else we can use it, the most popular use of refs in React is through ForwardRefs&lt;/p&gt;
&lt;h2&gt;
  
  
  ForwardRefs
&lt;/h2&gt;

&lt;p&gt;Forwarding refs in React is a technique that allows you to pass a ref down to a child component. This is particularly useful when you need direct access to a DOM element or a class component instance which is available in a child component. &lt;/p&gt;

&lt;p&gt;Sounds kinda similar to passing props to children right?  &lt;/p&gt;

&lt;p&gt;But ForwardRefs holds a different purpose, it allows you to pass refs through components to a child, usually to access a DOM element or a class component instance directly for imperative operations. This is not about passing down data for rendering like with props but about giving a parent component direct access to a DOM node managed by a child. &lt;/p&gt;

&lt;p&gt;Normally, refs are not "passable" through components because they are not part of the component's props. However, React provides the React.forwardRef API to solve this problem.&lt;/p&gt;

&lt;p&gt;Here is a code snippet which shows how you pass a ref from a parent component to a child a component&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const ChildComponent = React.forwardRef((props, ref) =&amp;gt; (
  &amp;lt;div ref={ref}&amp;gt;I'm a child&amp;lt;/div&amp;gt;
));

function ParentComponent() {
  const childRef = useRef();

  useEffect(() =&amp;gt; {
    console.log(childRef.current); // Directly access the child's div
  }, []);

  return &amp;lt;ChildComponent ref={childRef} /&amp;gt;;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This way my parent component gets the whole reference of the child Component’s any element.&lt;/p&gt;

&lt;p&gt;Now I was curious, that why do I need to prefix my functional component with this  ‘React.forwardRef’? I mean why can't I just pass my ref like any other prop?&lt;/p&gt;

&lt;p&gt;Turns out if I try to pass a ref like this &lt;code&gt;&amp;lt;ChildComponent ref={childRef} /&amp;gt;&lt;/code&gt; , and in the child component there is no prefix of &lt;code&gt;React.forwardRef&lt;/code&gt;, it won’t work the way it was intended.&lt;/p&gt;

&lt;p&gt;This happens because, In the Child component, we are trying to destructure ref from props, &lt;/p&gt;

&lt;p&gt;This is problematic because ref is a reserved keyword in React. It's not passed into your component as a regular prop. React treats ref (and key) specially, and they are not part of the props object passed to your component. Thus, attempting to destructure ref from props like this won't work because ref will not exist on the props object.&lt;/p&gt;

&lt;p&gt;Now it may sound like bypassing React’s conventions but I tried to find a work around where I can pass the ref from parent to child component without using &lt;code&gt;React.forwardRef&lt;/code&gt;, Here is the snippet for that -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function ChildComp({Tref}) {
  return (
    &amp;lt;div ref={Tref} &amp;gt;App&amp;lt;/div&amp;gt;
  )
}


function App() {
  const childRef = useRef();


  useEffect(() =&amp;gt; {
    console.log(childRef.current); // Directly access the child's div
  }, []);


  return &amp;lt;ChildComp Tref={childRef} /&amp;gt;;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because ref is a reserved keyword I just added a ‘T’ in the starting and now it works like any other prop, I can pass it to the child component and it returns me the reference of the child component’s element to the parent component.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;BUT&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This method was just because I was curious to know what I can do with this, in a production environment, practices or experiments like these should not be done, and there are many reasons for that. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;DX (Developer Experience)&lt;/strong&gt; -  When other developers will read your code if they’ll see the prefix &lt;code&gt;React.forwardRef&lt;/code&gt;, they’ll know that you are passing refs from parent component to child component at the first glance, which increases code maintainability&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Future React Compatibility&lt;/strong&gt; -  React's development team continually improves the framework. While your workaround might work now, there's no guarantee it will be compatible with future versions of React. Following the recommended patterns ensures better forward compatibility.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Static Typing&lt;/strong&gt; -  If you're using TypeScript or PropTypes for type checking, &lt;code&gt;React.forwardRef&lt;/code&gt; integrates smoothly, allowing you to specify types for both props and refs. Custom patterns might require additional effort to type check correctly.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;DevTools Inspection&lt;/strong&gt; - Components wrapped in &lt;code&gt;React.forwardRef&lt;/code&gt; are better supported by React DevTools. The forwarding of refs is a recognized pattern, and such components can be inspected more intuitively in the DevTools, improving debuggability.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Although none of these points, point to a breaking problem where the code won't even run the way it was intended, it is still recommended to use &lt;code&gt;React.forwardRef&lt;/code&gt;, the way it is intended to use.&lt;/p&gt;

&lt;p&gt;Well that was all regarding refs from my side, here is a takeaway from this blog&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Understanding Refs&lt;/strong&gt; -  Refs provide a way to access DOM nodes directly within React components, bridging the gap between React's virtual DOM and the actual DOM.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;useRef vs. useState&lt;/strong&gt; -  We discussed why useRef is the preferred method for referencing DOM nodes without triggering unnecessary re-renders, in contrast to useState, which is designed for data that impacts the UI and requires re-rendering.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Practical Applications&lt;/strong&gt; - Through examples, we’ve seen how refs can be used for focusing elements, measuring them, and more complex tasks like forwarding refs to access DOM elements in child components.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Best Practices&lt;/strong&gt;: While refs are powerful, we emphasized their proper use and the importance of not overusing them, adhering to React’s design principles for clean and maintainable code.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Remember, while ref is a great tool in the React, it comes with the responsibility of using it judiciously to enhance, rather than complicate, your components’ interactions with the DOM.&lt;/p&gt;

&lt;p&gt;Well, that’s all the doubts and insights I had in mind regarding Refs, &lt;br&gt;
Have you encountered situations where refs were the hero of your project? Or perhaps a challenge that seemed tailor-made for a ref solution but ended up being solved differently? Share your experiences, tips, or questions in the comments below. &lt;/p&gt;

&lt;p&gt;Additionally, if you’ve found creative uses for refs or have insights on pitfalls to avoid, let’s hear about them! Engaging with each other’s stories and strategies can lead to a deeper understanding of React’s capabilities.&lt;/p&gt;

&lt;p&gt;Thanks for reading this far 😁&lt;/p&gt;

</description>
      <category>programming</category>
      <category>javascript</category>
      <category>react</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Listening on the Network: What does it mean?</title>
      <dc:creator>Samyak Jain</dc:creator>
      <pubDate>Wed, 27 Mar 2024 07:23:27 +0000</pubDate>
      <link>https://dev.to/samyak112/listening-on-the-network-what-does-it-mean-1if1</link>
      <guid>https://dev.to/samyak112/listening-on-the-network-what-does-it-mean-1if1</guid>
      <description>&lt;p&gt;What does “listening” mean in terms of networking?&lt;/p&gt;

&lt;p&gt;I am trying to make an HTTP server from scratch and had to understand about TCP listeners, so when I started to read about it and I was reading that TCP listeners do this or that and you bind an IP address to it with port number the only thing that was confusing me was that what does it mean “listening”? &lt;/p&gt;

&lt;p&gt;I mean how does it listen? Is there a fixed interval? How is my Rust program is receiving this data? Where is this data coming from? Is there a fixed interval in which we check again if any request came?&lt;/p&gt;

&lt;p&gt;So after doing some research, I got to know that - &lt;/p&gt;

&lt;p&gt;When we say that a TcpListener instance in Rust is "listening" on a specific IP address and port, we're using a networking metaphor to describe the way the operating system monitors network traffic for connection attempts that match certain criteria (in this case, the IP address and port number)&lt;br&gt;
The Concept of Binding&lt;/p&gt;

&lt;h2&gt;
  
  
  Binding to an IP Address and Port
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;IP Address:&lt;/strong&gt; Every device connected to a network has an IP address, which is used to identify it on the network. When a TCP listener is bound to an IP address, it tells the operating system that this particular application is interested in network traffic sent to that address.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Port:&lt;/strong&gt; A port is a numerical identifier in networking used to specify a specific application or service on a device. Since a single device can run multiple networked applications simultaneously, the port number helps differentiate which application should handle incoming data.&lt;/p&gt;

&lt;h2&gt;
  
  
  What exactly is Binding?
&lt;/h2&gt;

&lt;p&gt;When you bind a server (like a Rust TcpListener) to a specific IP address, you're telling the server to listen for incoming connections on that IP address.&lt;/p&gt;

&lt;p&gt;I was confused about what Binding means. Like does it mean from which address I’ll receive data? Or what?&lt;/p&gt;

&lt;p&gt;So I tried to understand this with an analogy - &lt;/p&gt;

&lt;p&gt;Imagine you have several mailboxes in front of your house, each with a different label or number. When someone sends you a letter, they choose one of those mailboxes based on the label or number you've given them.&lt;/p&gt;

&lt;p&gt;Binding is like deciding which mailbox you’re going to check for mail. If you decide to only check the mailbox labeled "Bills," it means you’re telling anyone who wants to send you something, "Hey, if you want me to see it, put it in the 'Bills' mailbox."&lt;/p&gt;

&lt;p&gt;Binding does not mean choosing from which addresses you'll accept request (or requests). Instead, it's about choosing which mailbox (among those at your house) you're going to use to receive any mail (or requests) sent to your house.&lt;/p&gt;

&lt;p&gt;Now in this analogy, it might feel like how my house has multiple mailboxes in front of it. Do is it mean that my laptop has multiple IP addresses? &lt;/p&gt;

&lt;p&gt;Well normally the NIC in a laptop has only one IP address configured but because in cloud platforms multiple websites are hosted on the same machine, the NIC with multiple IP addresses helps, so on the same machine different IP addresses can get requests for themselves without interfering with each other.&lt;/p&gt;

&lt;p&gt;Now back to how listening works theoretically&lt;br&gt;
&lt;strong&gt;Operating System's Role:&lt;/strong&gt; The operating system keeps track of all the IP addresses and ports that applications are listening on. When network packets arrive at the device, the operating system checks the destination IP address and port number against this list. &lt;/p&gt;

&lt;p&gt;Again here you can see that the operating system checks the destination of the IP address and the port number, so basically checking if the machine has multiple IP addresses configured and then to which one OS should send the request to.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Network Traffic Filtering:&lt;/strong&gt; If the destination IP and port of an incoming packet match an application that's listening (i.e., our TcpListener), the operating system forwards this packet to that application. If not, the packet is ignored or rejected based on the system's network rules.&lt;/p&gt;

&lt;h2&gt;
  
  
  How does the OS "listen" to the request?
&lt;/h2&gt;

&lt;p&gt;The process by which an operating system listens for and handles incoming network requests to a bound IP address and port doesn't typically rely on a timer that checks periodically (like every 1 second). Instead, the mechanism is more efficient and event-driven, utilizing the network stack and hardware capabilities to immediately notify the operating system of incoming packets. Here’s a simplified overview of how this works:&lt;/p&gt;

&lt;h2&gt;
  
  
  Network Interface Controller (NIC)
&lt;/h2&gt;

&lt;p&gt;Each network packet arriving at a device first reaches the Network Interface Controller (NIC), the hardware component that connects a computer to a network. The NIC operates at a low level, handling the physical transmission and reception of data packets over the network medium.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;so essentially it's neither the TCP listener nor the OS who is actually listening but the NIC.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The initial detection of incoming network packets is indeed a hardware-level function, primarily managed by the Network Interface Controller (NIC). The NIC is the first point of contact for all incoming data from the network. It operates at a low level, directly interfacing with the physical network medium (like Ethernet, Wi-Fi, etc.), and is responsible for the physical transmission and reception of data packets.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;So what happens when concurrent requests are received by an NIC, I mean it can detect only one at a time or unlimited?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The Network Interface Controller (NIC) plays a crucial role in handling incoming network traffic, including dealing with concurrent requests. While the NIC is extremely fast and can process a vast number of packets per second, it indeed deals with one packet at a time due to the serial nature of network communication. &lt;/p&gt;

&lt;p&gt;However, the combination of high-speed operation, buffering, and efficient handling by the operating system and application software makes it capable of managing what appears as concurrent requests. Here's how it works:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Serial Processing:&lt;/strong&gt; Physically, the NIC receives packets one at a time because a network cable or wireless connection can only carry one packet's worth of data at any instant. However, because packets are small and the NIC operates at a very high speed, it can process many packets in a very short amount of time, giving the impression of parallelism.&lt;/p&gt;

&lt;p&gt;Now again the question that bugged me here was - &lt;/p&gt;

&lt;h2&gt;
  
  
  How something can send a request to another thing without the other thing waiting for it?
&lt;/h2&gt;

&lt;p&gt;Like in our current discussion, NIC is sending some information to the CPU but the CPU is working on something else, how does the CPU exactly receive it?&lt;/p&gt;

&lt;p&gt;The process which is being described here is called &lt;strong&gt;asynchronous communication&lt;/strong&gt;, where one component can send a signal or message to another component without the recipient actively waiting for it at that moment. Let's break down how this works in the context of the NIC sending an interrupt request (IRQ) to the CPU:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interrupt Controller:&lt;/strong&gt; Modern computer systems include an interrupt controller, a hardware component responsible for managing interrupts from various devices, including the NIC. The interrupt controller is constantly monitoring for incoming interrupts from different sources.&lt;/p&gt;

&lt;p&gt;The main purpose of an interrupt controller is to arbitrate between multiple devices that may need the CPU's attention simultaneously. It ensures that each device gets a fair chance to interrupt the CPU when necessary.&lt;/p&gt;

&lt;p&gt;When a hardware device, such as a network interface card (NIC) or a keyboard, needs to communicate with the CPU, it sends an interrupt signal to the interrupt controller.&lt;/p&gt;

&lt;p&gt;Yes, that's correct! Even the Keystrokes from a keyboard can indeed generate interrupts in a computer system. When you press a key on your keyboard, it sends an electrical signal to the keyboard controller, which in turn generates an interrupt to the CPU via the interrupt controller. This interrupt informs the CPU that there is new input from the keyboard that needs to be processed.&lt;/p&gt;

&lt;p&gt;So this explains how the data reaches the OS from the NIC (using the interrupt Handling), Now how does it reach the TCP listener?&lt;/p&gt;

&lt;p&gt;That's a Topic for our next discussion 😁, Thanks for reading this far.&lt;/p&gt;

</description>
      <category>networking</category>
      <category>network</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Strings in Rust</title>
      <dc:creator>Samyak Jain</dc:creator>
      <pubDate>Tue, 12 Mar 2024 04:28:44 +0000</pubDate>
      <link>https://dev.to/samyak112/strings-in-rust-4elm</link>
      <guid>https://dev.to/samyak112/strings-in-rust-4elm</guid>
      <description>&lt;p&gt;Today we are going to understand strings in Rust, which includes learning about String and &amp;amp;str, let's start understanding each and I'll try to clear some of the doubts that I had while reading about them. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&amp;amp;str&lt;/strong&gt; - &lt;/p&gt;

&lt;p&gt;&amp;amp;str is an immutable, UTF-8 encoded string slice. Since &amp;amp;str is immutable you cannot modify its content. It is a borrowed reference to a position of an existing string and it does not own the data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;String&lt;/strong&gt; - &lt;/p&gt;

&lt;p&gt;String is a growable, heap-allocated string. It is owned and mutable, allowing dynamic modifications to its content.&lt;br&gt;
It is a type provided by the Rust standard library and is not a primitive type like str. It is a heap-allocated, UTF-8 encoded string that can be dynamically resized.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;This is how a mutable string is created - 
fn main() {
    let test = "hello".to_string();
    println!("{test}");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Doubts
&lt;/h2&gt;

&lt;p&gt;Now this is just a very brief overview of both and I had some problems in the working of both, &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;In &amp;amp;str, how is it by default a borrowed reference of an existing string? If I just created a variable like this &lt;code&gt;let test = "hello";&lt;/code&gt; , how is this a borrowed reference of an existing string? I mean I just created this right?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In mutable string, who do I need to use .to_string(), isn't that already a string?&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;To answer and understand the reasoning behind these questions we have to first understand string literals in Rust.&lt;/p&gt;

&lt;h2&gt;
  
  
  String Literals
&lt;/h2&gt;

&lt;p&gt;String literals are sequences of characters defined directly in your source code, like "hello". They are immutable and embedded in the program's binary, specifically in a read-only section. &lt;/p&gt;

&lt;p&gt;So when you create a variable like let greeting = "hello world"; And run your program, the string literal "hello world" is saved in the binary at compile time. This means that as soon as your program is compiled, the string literal "hello world" is already placed in the read-only section of the compiled binary. This process is independent of declaring any variables that might refer to it. &lt;/p&gt;

&lt;p&gt;Now When the code actually runs after getting compiled (Which already has the "hello world" string literal stored), the greeting is initialized as a borrowed reference (&amp;amp;'static str) to the string literal at runtime. Because it is already saved in the binary storage. The reference &lt;code&gt;greeting&lt;/code&gt; points to the memory location within the read-only section of the binary where "hello world" is stored.&lt;/p&gt;

&lt;p&gt;This explains how even after just creating the greeting variable, how it directly becomes a borrowed reference to a pre-existing string, because the string is already stored during compile time, and because by default string is immutable there is no point to make a copy of it, thats why it just directly refers to the binary storage.&lt;/p&gt;

&lt;p&gt;This also explains why we need to use &lt;code&gt;.to_string()&lt;/code&gt; to create a mutable string, because by default the string literal is stored as a read-only binary, so to create a string that can be modified we use &lt;code&gt;.to_string()&lt;/code&gt;, which creates a copy of the original string literal that is allocated on the heap. This means it can change size (grow or shrink) as needed during runtime. &lt;/p&gt;

&lt;p&gt;Based on this explanation I try to think of string literals in Rust as the base form of string data, which depending on how you use it can either remain an immutable str or be 'converted' into a mutable String. &lt;/p&gt;

&lt;p&gt;Do share some scenarios in comments where &amp;amp;str would be more beneficial than a mutable string, I mean I know that if i use &amp;amp;str , it would just refer to some other storage instead of creating a copy , but other than that is there any other benefit to use &amp;amp;str? &lt;/p&gt;

&lt;p&gt;Now Let's discuss how this transformation of string literal to either &amp;amp;str or String happens.&lt;/p&gt;

&lt;h2&gt;
  
  
  Transformation
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Immutable &amp;amp;str&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When you directly use a string literal in your Rust code, such as &lt;code&gt;let greeting = "Hello, world!";&lt;/code&gt;, &lt;code&gt;greeting&lt;/code&gt; is an immutable &lt;code&gt;&amp;amp;'static str&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;This means it's a borrowed reference to a string slice with a 'static lifetime, pointing to data embedded in the read-only section of the binary.&lt;/p&gt;

&lt;p&gt;This form is efficient for read-only operations, passing around string data without taking ownership, and for use cases where the string data does not need to change.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mutable String&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you need a mutable, growable version of the string data, you can convert the string literal into a String by using methods like &lt;code&gt;.to_string()&lt;/code&gt; or &lt;code&gt;String::from()&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;For example, let mut greeting = "Hello, world!".to_string(); creates a String from the string literal.&lt;br&gt;
The String type is heap-allocated, growable, and mutable. It allows you to modify the string data, such as appending text or changing characters.&lt;/p&gt;

&lt;p&gt;Converting a string literal to a String involves copying the data from the binary's read-only section into dynamically allocated memory on the heap. This operation gives you full ownership and control over the copied data, including the ability to modify it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Working under the hood
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Memory Allocation&lt;/strong&gt;: The original string literal remains in the read-only segment of your program's binary, untouched. The String object involves a separate allocation of memory on the heap, where the contents of the string literal are copied.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Data Duplication&lt;/strong&gt;: This means you now have two copies of the "Hello, world!" string data: one embedded in the read-only memory as part of the program's binary (the original string literal), and another stored in the heap memory as a String object (the result of .to_string()).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mutability and Ownership&lt;/strong&gt;: The key difference between these two is that the &amp;amp;'static str reference to the string literal is immutable and has a static lifetime, while the String object is mutable, growable, and owned by the greeting variable. This ownership comes with the Rust guarantees of memory safety, ensuring that the heap memory will be properly deallocated when greeting goes out of scope or is no longer needed.&lt;/p&gt;

&lt;p&gt;so now that we understand that the mutable hello world's ownership is with &lt;code&gt;greeting&lt;/code&gt; variable, then who has the ownership of the string literal?&lt;/p&gt;

&lt;p&gt;String literals do not have an "owner" in the traditional sense used for heap-allocated memory in Rust. Instead, they are baked into the program's binary and loaded into memory as part of the program's execution context. They are immutable and globally accessible anywhere in the program.&lt;/p&gt;

&lt;p&gt;These were some points that piqued my interest in understanding strings in Rust, Do let me know if I missed something related to strings or if I miscommunicated some concept.&lt;/p&gt;

&lt;p&gt;Thanks for reading this far 😁.&lt;/p&gt;

</description>
      <category>rust</category>
      <category>programming</category>
      <category>learning</category>
      <category>softwaredevelopment</category>
    </item>
    <item>
      <title>What is Transpilation?</title>
      <dc:creator>Samyak Jain</dc:creator>
      <pubDate>Tue, 30 Jan 2024 19:17:04 +0000</pubDate>
      <link>https://dev.to/samyak112/what-is-transpilation-4hl0</link>
      <guid>https://dev.to/samyak112/what-is-transpilation-4hl0</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;So there was this ruckus in my head about some words like babel, webpack, transpilation and these are some words that you hear a lot if you are a web developer.&lt;/p&gt;

&lt;p&gt;The kind of words that make you pause, and wonder, "Am I supposed to know what these mean?" I mean yeah you can skip it, it won't really hurt your development, but it's good to know that what's happening underneath. &lt;/p&gt;

&lt;p&gt;Today we'll try to understand these words, No fancy jargon, just plain talk about what these things actually are.&lt;/p&gt;

&lt;h2&gt;
  
  
  Transpilation
&lt;/h2&gt;

&lt;p&gt;As programmers, we like to use the most recent features, I mean who doesn't like using a spread operator which is a feature introduced in ES6, but on the other hand, how to make our modern code work on older engines that don't understand ES6 or JSX or Typescript? &lt;/p&gt;

&lt;p&gt;Browser's &lt;a href="https://dev.to/samyak112/what-is-a-javascript-engine-4gjo"&gt;JS engines&lt;/a&gt; are not configured to understand all of this, they only understand Javascript and yeah most of the browsers these days do support ES6 but it still does not solves the problem of them not understanding JSX or typescript. That's where Transpilation comes in. &lt;/p&gt;

&lt;p&gt;Transpilation, short for "source-to-source compilation," is the process of converting source code written in one programming language to equivalent code in another language or another version of the same language.&lt;/p&gt;

&lt;p&gt;source to source compilation? We are talking about transpilation, right? Where did this compilation come from all of a sudden? &lt;/p&gt;

&lt;p&gt;Well, Transpilation is a subset of compilation, there is also a lot of debate about whether there should even be a separate word for this process. &lt;/p&gt;

&lt;p&gt;Well after reading a lot of debate in my opinion Transpilation feels like a word of choice, you like to have some distinction? Call Conversion of code written in one language to another or equivalent but different version as Transpilation, You think it's too similar to be given a different name call it a subset of a compiler.&lt;/p&gt;

&lt;p&gt;Even Babel, the tool which is the most used tool for transpilation addresses itself as a compiler. &lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8a1m95rfw366wbmmc48s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8a1m95rfw366wbmmc48s.png" alt="babel being a compiler" width="800" height="184"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now that we have made that clear lets continue talking more about transpilation, &lt;/p&gt;

&lt;p&gt;So by now, we have understood that what a transpiler does, it takes my source code and converts it to JS engine compatible JS code. But how does it do it?&lt;/p&gt;

&lt;p&gt;If you know how the JS engine works it will be a little easier for you, for others do not worry, &lt;/p&gt;

&lt;p&gt;The process typically involves the following key steps:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lexical Analysis&lt;/strong&gt;&lt;br&gt;
The transpiler starts by breaking down the source code into individual tokens, such as keywords, operators, and identifiers.&lt;br&gt;
This phase is known as lexical analysis and involves creating a stream of tokens from the source code.&lt;/p&gt;

&lt;p&gt;Here is an example - &lt;br&gt;
&lt;code&gt;let x = 10 + 5;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Its tokenized form will look like - "let", "x", "=", "10", "+", "5", ";"&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Abstract Syntax Tree (AST) Creation&lt;/strong&gt;&lt;br&gt;
The stream of tokens is then used to build an Abstract Syntax Tree (AST). The AST represents the hierarchical structure of the code, making it easier to analyze and manipulate.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl7z1s1doqcvl6j12r1sl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl7z1s1doqcvl6j12r1sl.png" alt="ast" width="337" height="149"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Transformation&lt;/strong&gt;&lt;br&gt;
The transpiler applies transformations to the AST. This step involves converting code written in the source language (e.g., ES6) into an equivalent representation in the target language (e.g., ES5).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Code Generation&lt;/strong&gt;&lt;br&gt;
The transformed AST is used to generate the final transpiled code. This code is designed to be compatible with the target environment or runtime.&lt;/p&gt;

&lt;p&gt;Now this is a very high-level understanding of how transpilation works and not exactly how transpilation works.&lt;/p&gt;
&lt;h2&gt;
  
  
  Transpilation of &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;Ok, we know that how transpilation works, but while reading about this a question struck me, what about let and const? I mean these keywords were introduced in ES6 they were not there in ES5, so I checked how this was being handled and I got to know that the transpiler converts &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; to &lt;code&gt;var&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;What?? converting let and const to var? Then what about all the concepts of hoisting and blocked &lt;a href="https://dev.to/samyak112/understanding-scope-in-javascript-1ge7"&gt;scope&lt;/a&gt;, well don't worry I was really confused too, well after searching a bit more, I tried this &lt;a href="https://jstool.gitlab.io/babel-es6-to-es5/" rel="noopener noreferrer"&gt;website&lt;/a&gt; which lets you write ES6 code and you can see ES5 equivalent of it.&lt;/p&gt;

&lt;p&gt;So I went there and I tried this snippet -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if(true){
  let a = 1
  console.log(a)
}
console.log(a)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;well, the output was interesting -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (true) {
  var _a = 1;
  console.log(_a);
}
console.log(a);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It created a behavior like that of &lt;code&gt;let&lt;/code&gt; even with &lt;code&gt;var&lt;/code&gt;, it smartly added an underscore inside the if block's &lt;code&gt;a&lt;/code&gt; variable so that it doesn't exist outside of the if block.&lt;/p&gt;

&lt;p&gt;Play around with this, try different things, and see what happens, let me know in the comments what you tried.&lt;/p&gt;

&lt;h2&gt;
  
  
  PolyFill
&lt;/h2&gt;

&lt;p&gt;Ok so now we know that how transpilation works cool cool cool, but transpilation basically translates the code right? What about the features that don't even exist in the previous version? Like if we take an example of ES6 to ES5 conversion, and talk about the &lt;code&gt;includes&lt;/code&gt; function, it didn't even existed in ES5. So how will we translate something that does not even exist there?&lt;/p&gt;

&lt;p&gt;You can try using that ES6 to ES5 converter and it will show the same code that you will try.&lt;/p&gt;

&lt;p&gt;Thats where poly filling comes in, the official definition of poly filling according to &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/Polyfill" rel="noopener noreferrer"&gt;MDN &lt;/a&gt; is -&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now how do you do polyfilling? Is it a software? Well, I was reading [Remy Sharp's] blog(&lt;a href="https://remysharp.com/2010/10/08/what-is-a-polyfill" rel="noopener noreferrer"&gt;https://remysharp.com/2010/10/08/what-is-a-polyfill&lt;/a&gt;) (Person who introduced the term), and some implementation of poly filling, I understood that poly filling is not some tool, its more of a concept that you apply in your code to increase compatibility of your application.&lt;/p&gt;

&lt;p&gt;Here is an analogy to help you understand the relationship between traditional transpilation and Poyfilling - &lt;/p&gt;

&lt;p&gt;Imagine that you got your hands on a time machine and you time travelled to ancient times, excited to talk to the people there, you forgot that the language is different and they won't understand what you are saying, so what will you do? &lt;/p&gt;

&lt;p&gt;You will &lt;strong&gt;transpile&lt;/strong&gt; your language to their language so that they can understand it. Now you want to talk more with these people and want to allow even communication from a distance, you thought of using the phone, but wait that did not exist at that time, how will you even translate a thing that did not even exist at that time? &lt;/p&gt;

&lt;p&gt;Well that's where poly filling can help you to bridge the gap, you collected two cups and joined them using a long string, and now you have kind of a phone for long-distance communication.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fujhxazk0hypzh8nlhk4a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fujhxazk0hypzh8nlhk4a.png" alt="polyfill analogy" width="239" height="211"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now I am still a little confused as if this is the right way to explain it. I mean &lt;code&gt;let&lt;/code&gt; and &lt;code&gt;const&lt;/code&gt; also don't exist in ES5 and it was translated, right? &lt;/p&gt;

&lt;p&gt;What I think is transpilers handle these by finding equivalent constructs, while polyfills are employed when introducing entirely new concepts. I mean the concept of the variable was still there in ES5 right, but a function that can tell whether an element exists or not in an array, that never even existed there. &lt;/p&gt;

&lt;p&gt;Let me know in the comments if you have a better explanation to address this.&lt;/p&gt;

&lt;h2&gt;
  
  
  How Transpilation happen in our Projects?
&lt;/h2&gt;

&lt;p&gt;Well, before reading about this topic, I didn't even know that this was happening, so I possibly can't configure Babel in my React project or in any other framework or library. &lt;/p&gt;

&lt;p&gt;So in popular frameworks and libraries like React, angular, etc., this is already pre-configured, like if I take the example of React, normally devs create a React environment through two ways -&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;CRA (Create react app)&lt;/li&gt;
&lt;li&gt;Using Vite&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now CRA under the hood uses Webpack which is a &lt;strong&gt;Bundler&lt;/strong&gt;. And another way I told you i.e 'Using Vite' well Vite is a bundler as well. Now we won't go in much depth about bundlers in this blog, but I'll give you an overview as it is necessary to understand, So bundlers like Webpack or Vite are tools that are used to merge two more JS files into one file to form a bundled file.&lt;/p&gt;

&lt;p&gt;But this is not all that these bundlers do, they also take care of transpiling for us, so when you run &lt;code&gt;npm run build&lt;/code&gt; in your terminal it creates an optimized bundled and transpiled code for you which you deploy. So you never get to know what happened. &lt;/p&gt;

&lt;p&gt;The need for transpilation is more in these frameworks and libraries more than that of vanilla JS projects because Vanilla JS projects have the only problem that 'what if someone ran this in ES5 browser' but that's not the case anymore, its really rare that there is any browser which does not supports ES6.&lt;/p&gt;

&lt;p&gt;But a library or framework like react which is written in JSX it needs to be transpiled every time because the browser has no clue about JSX.&lt;/p&gt;

&lt;p&gt;Now there was one last thing that I was confused about, My confusion was that &lt;/p&gt;

&lt;p&gt;'ok I ran &lt;code&gt;npm run build&lt;/code&gt; and my code got transpiled and all good now browser will have no problem understanding my JSX.' &lt;br&gt;
&lt;strong&gt;But what about during development?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I had questions like - &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Is it getting re-transpiled on the go?&lt;/li&gt;
&lt;li&gt;If I remove one semicolon from my code the whole code gets retranspiled?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Well if removing one semicolon were to trigger a full re-transpilation then Developing a web app wouldn't be easy, because if you are maintaining a huge codebase where you are continuously making changes and you have to wait for like 30 seconds to 1 minute because you have this huge code base, your Developer Experience and your Productivity both would be very bad.&lt;/p&gt;

&lt;p&gt;That's where bundlers like Webpack and Vite show the magic, so these bundlers have something called HMR (Hot Module Replacement)&lt;/p&gt;

&lt;p&gt;It smartly re-transpile only the modules that actually changed and not the entire application. Once the modules (which were changed) are re-transpiled, the new code is injected into the running application on the fly.&lt;/p&gt;

&lt;p&gt;How does it 'inject' code in my application on the fly? Well when our frontend server starts a web socket connection is created between our frontend server and browser, and when something changes, this information is sent through a browser using a web socket. &lt;/p&gt;

&lt;p&gt;Yeah!! Sounds really interesting right? And unbelievable right? I mean I thought I at least knew my front end, I thought I knew everything happening in my front end and how it was happening. But here we are, a WebSocket connection is being executed through my front end and I didn't even know.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh49h1rjo94k421qvcsyz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh49h1rjo94k421qvcsyz.png" alt="web socket" width="800" height="359"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I wanted to test this, so I tried turning this HMR feature off through the web pack config and this was the result. &lt;/p&gt;

&lt;p&gt;So to test this by selecting all of the text, changing one line, and saving it and this was the result.&lt;/p&gt;

&lt;p&gt;HMR ON - &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F147vgc1x64veqn5ixb47.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F147vgc1x64veqn5ixb47.gif" alt="HMR ON" width="1024" height="1024"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You see how the text changed and neither the page reloaded nor the text selection went away.&lt;/p&gt;

&lt;p&gt;HMR OFF&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fp5sjzu79fjtysrrqh91s.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fp5sjzu79fjtysrrqh91s.gif" alt="HMROFF" width="1024" height="1024"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here you see the page reloaded, so there is no HMR and the whole transpilation is being done again from scratch.&lt;/p&gt;

&lt;h2&gt;
  
  
  How can you try this?
&lt;/h2&gt;

&lt;p&gt;For testing this create a Create react app, and then run this command &lt;code&gt;npm run eject&lt;/code&gt;, after this you will be able to see the config file&lt;br&gt;
which contains the configuration of webpack, in the webpack.config.js file change this variable &lt;code&gt;shouldUseReactRefresh&lt;/code&gt; to false, restart the server, and just try changing something.&lt;/p&gt;

&lt;p&gt;Let me know in the comments what happened.&lt;/p&gt;

&lt;p&gt;We will talk about the working of HMR and the frontend server in another blog, it's a big topic, and need its own blog for that.&lt;/p&gt;

&lt;p&gt;So there it is, we understood the fancy and technical words like Webpack, Babel, and Transpilation and learned some more things on the way, we talked about how transpilation works, how a newbie developer like me or someone else doesn't even need to know this stuff to run a project. And much more.&lt;/p&gt;

&lt;p&gt;Thanks for reading this far😁.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>learning</category>
      <category>programming</category>
    </item>
    <item>
      <title>Are Random numbers really random?</title>
      <dc:creator>Samyak Jain</dc:creator>
      <pubDate>Mon, 22 Jan 2024 09:19:01 +0000</pubDate>
      <link>https://dev.to/samyak112/are-random-numbers-really-random-1ee7</link>
      <guid>https://dev.to/samyak112/are-random-numbers-really-random-1ee7</guid>
      <description>&lt;p&gt;So recently a thought struck me that we use random functions in our software all the time right? Either in games or in machine learning models, cryptographic software, etc.&lt;/p&gt;

&lt;p&gt;But are these "randomly" generated numbers are actually random? I mean there must be some algorithm that calculates this so-called random number right? And if it's calculated it's not really "random" now is it?&lt;/p&gt;

&lt;p&gt;So today I'll try to explain how random is a random number in programming languages.&lt;/p&gt;

&lt;p&gt;So all the random functions in different programming languages like Math.random() in Javascript are not "True" random number generators, they are called PRNGs (Psuedo Random Number Generators)&lt;/p&gt;

&lt;p&gt;The word Psuedo is self-explanatory that these random generators are not truly random. So now the question that arises is - Okay random number generators are not truly random then to what extent these numbers are random? &lt;/p&gt;

&lt;p&gt;This is the question that measures the quality of a PRNG. &lt;/p&gt;

&lt;p&gt;There are many algorithms that are used to generate random numbers, but what all of them have in common is a &lt;strong&gt;Period&lt;/strong&gt; and a &lt;strong&gt;Seed&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Seed
&lt;/h2&gt;

&lt;p&gt;A seed is an initial value that is passed in the random function to create a random number. &lt;br&gt;
To understand how a seed works in a PRNG, Let's take a look at an algorithm called LCG (Linear congruential generator)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LCG&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1a2aedpbmhf489acmi3j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1a2aedpbmhf489acmi3j.png" alt="lcg" width="720" height="240"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For those familiar with random number generator algorithms, do you have a favorite? Whether it's LCG, Xorshift, or another algorithm, do share your preferences and experiences with different generators.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Back to the example of LCG&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So the formula of an LCG is X = (a.Xcurrent + C) % mod m&lt;br&gt;
where,&lt;br&gt;
X is the sequence of pseudo-random numbers&lt;br&gt;
m, ( &amp;gt; 0) the modulus&lt;br&gt;
a, (0, m) the multiplier&lt;br&gt;
c, (0, m) the increment&lt;br&gt;
Xcurrent ,  [0, m) – Current Seed&lt;/p&gt;

&lt;p&gt;So what happens is once the initial seed is selected it is passed in this equation where Xcurrent is the only thing that is variable and everything else is a constant, so the seed is passed in this equation as Xcurrent, and the operations are done, once the answer is generated, next time the previous answer is used as seed and so on.  &lt;/p&gt;

&lt;p&gt;Here is an example of how does it look&lt;/p&gt;

&lt;p&gt;Let's consider an LCG with a specific set of constants: &lt;/p&gt;

&lt;p&gt;&lt;code&gt;a = 7,&lt;/code&gt;&lt;br&gt;
&lt;code&gt;c = 5,&lt;/code&gt;&lt;br&gt;
&lt;code&gt;m = 32,&lt;/code&gt;&lt;br&gt;
and initial seed as 3&lt;/p&gt;

&lt;p&gt;so&lt;br&gt;
&lt;code&gt;1. X = (7*3 + 5) mod 32 = 26 =&amp;gt; X = 26&lt;/code&gt;&lt;br&gt;
&lt;code&gt;2. X = (7*26 + 5) mod 32 = 11 =&amp;gt; X = 11&lt;/code&gt;&lt;br&gt;
&lt;code&gt;3. X = (7*11 + 5) mod 32 = 22 =&amp;gt; X = 22&lt;/code&gt;&lt;br&gt;
&lt;code&gt;4. X = (7*22 + 5) mod 32 = 19 =&amp;gt; X = 19&lt;/code&gt;&lt;br&gt;
&lt;code&gt;5. X = (7*19 + 5) mod 32 = 26 =&amp;gt; X = 26&lt;/code&gt;&lt;br&gt;
&lt;code&gt;6. X = (7*26 + 5) mod 32 = 11 =&amp;gt; X = 11&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This is how once a seed is decided the generated value is used as a seed to create the next random number, Now am sure you must have noticed something strange in this sequence right? After point 4 the sequence started to repeat. First 26 and then 11 and so on?&lt;/p&gt;

&lt;h2&gt;
  
  
  Period
&lt;/h2&gt;

&lt;p&gt;So there are multiple algorithms to generate a PRN, like LCG or Xorshift128+ (Used by the v8 engine) but what all of them have in common is that there is a limit to producing random numbers before which they start to repeat the sequence. This is what is known as a &lt;strong&gt;Period&lt;/strong&gt;. Every PRNG has repeatability after a point, now how long the sequence is before the numbers start to repeat is what tests the quality of the PRNG.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why there is a Period?
&lt;/h2&gt;

&lt;p&gt;But why does this happen? Why do numbers start to repeat? &lt;/p&gt;

&lt;p&gt;It might sound like a silly question, but it was bugging me so I tried to understand this, &lt;/p&gt;

&lt;p&gt;what I understood is that this happens because computers have a limit to generate numbers, sure there are infinite numbers, but there is a limit till which a computer can comprehend,  like in a 64-bit architecture that limit is −9,223,372,036,854,775,808 to 9,223,372,036,854,775,808 so computer needs to maintain the number in that limit. &lt;/p&gt;

&lt;p&gt;So algorithms try to keep this number in range like in LCG after multiplication and addition in the seed, a modulus is performed so that the number does not keep increasing till the point that the computer can't comprehend it anymore. &lt;/p&gt;

&lt;p&gt;And if there are only finite numbers that the computer can generate through an algorithm then after a while it's inevitable that the seed that started the sequence will be generated and once that number is generated the whole sequence will be repeated.&lt;/p&gt;

&lt;p&gt;So yeah if you know the seed you can predict the whole sequence.&lt;br&gt;
Here is a &lt;a href="https://replit.com/@Samyakjain46/PRNG#main.py" rel="noopener noreferrer"&gt;replit link&lt;/a&gt; for you to try I have set a seed and ran a loop for 10 values no matter how many times you run the loop it will have the same result.&lt;/p&gt;

&lt;p&gt;Now if you are a Minecraft player you must have heard "seed" before as well. When you enter a seed that is shared by someone else you also get spawned in the same area as them. Why? Because Minecraft uses a random generator to create an area, and if it's random then it also has some seed, and if you have that same seed then yes you will get the same output.&lt;/p&gt;

&lt;p&gt;Have you ever played a game that allowed you to input a 'seed' for generating the game world? Share your experience and any interesting outcomes!&lt;/p&gt;

&lt;p&gt;While talking about PRNGs it is important to note that PRNGs are not cryptographically secure as also mentioned in the &lt;a href="https://v8.dev/blog/math-random" rel="noopener noreferrer"&gt;v8 Docs&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;It is not recommended for hashing, signature generation, and encryption/decryption.&lt;/p&gt;

&lt;p&gt;For those purposes you can use &lt;code&gt;window.crypto.getRandomValues&lt;/code&gt; "but" at the cost of performance.&lt;/p&gt;

&lt;p&gt;So why do we use PRNGs if it has so many flaws?&lt;/p&gt;

&lt;p&gt;I mean you know the seed and voilà you know the sequence, it's not cryptographically secure then where is it used?&lt;/p&gt;

&lt;h2&gt;
  
  
  Applications of PRNGs
&lt;/h2&gt;

&lt;p&gt;Well PRNGs are very efficient and fast they are very useful in games like you want to spawn the player at a random place and spawn some buildings randomly, but you don't want it to be truly random and efficient because games need to render everything fast.&lt;/p&gt;

&lt;p&gt;If we go back to the example of Minecraft, Minecraft does not create the whole environment as soon as you enter in the game, because if that had been the case there would have been a great toll on the game and a huge storage space used by the game. Instead, it creates environments on the fly as players start to move in a direction.&lt;/p&gt;

&lt;p&gt;Minecraft features randomly generated structures such as villages, temples, and dungeons. The placement of these structures adds surprises to the landscape, and their designs vary based on procedural algorithms.&lt;/p&gt;

&lt;p&gt;Advantages of Procedural Generation:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmk7vm8gv7d36cdxuxstd.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmk7vm8gv7d36cdxuxstd.gif" alt="Minecraftvideo" width="1024" height="1024"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Scalability: Minecraft's procedural generation allows the game to scale infinitely without the need for massive storage space for pre-designed maps.&lt;/p&gt;

&lt;p&gt;Exploration: As players traverse the world, new chunks of terrain are generated dynamically, providing a sense of discovery and unpredictability.&lt;/p&gt;

&lt;p&gt;Replayability: Different seed values and the randomness in terrain generation enhance the replayability of the game, as players can experience entirely new worlds with each playthrough.&lt;/p&gt;

&lt;p&gt;Impact on Performance:&lt;/p&gt;

&lt;p&gt;Generating terrain in real-time as players explore reduces the initial loading time and minimizes the demand on system resources compared to loading an entire pre-designed world.&lt;/p&gt;

&lt;p&gt;PRNGs are also used for debugging, where engineers can pre-define the seed and can run iterations on a fixed sequence to run some tests.&lt;/p&gt;

&lt;p&gt;Truly Random Number Generators are great but they come at the cost of performance so it's up to us to decide the tradeoff. Overall it was a great topic to read and learn about.&lt;/p&gt;

&lt;p&gt;As a developer, how often do you use random number generators in your projects? Do you have any favorite algorithms or tips for ensuring randomness in your applications?&lt;/p&gt;

&lt;p&gt;In conclusion, while pseudorandom number generators (PRNGs) play a crucial role in various applications, from gaming to simulations, understanding their limitations is equally important. The predictable nature of PRNGs, marked by periods and seed-dependent sequences, raises questions about their suitability for cryptographic purposes. As developers, we navigate the trade-off between efficiency and true randomness, opting for PRNGs in scenarios where rapid, reproducible results are paramount. Reflect on the challenges posed by the inherent predictability of PRNGs and consider: How do we balance the convenience of PRNGs with the need for cryptographic security in our applications?&lt;/p&gt;

&lt;p&gt;If there is anything that I missed about PRNGs that could have made the blog better or you have any questions related to it please let me know in the comments.&lt;/p&gt;

&lt;p&gt;Thanks for reading this far😁.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>learning</category>
      <category>security</category>
    </item>
    <item>
      <title>What is a Javascript Engine?</title>
      <dc:creator>Samyak Jain</dc:creator>
      <pubDate>Wed, 17 Jan 2024 07:55:04 +0000</pubDate>
      <link>https://dev.to/samyak112/what-is-a-javascript-engine-4gjo</link>
      <guid>https://dev.to/samyak112/what-is-a-javascript-engine-4gjo</guid>
      <description>&lt;p&gt;Ever Wondered what happens when you write a Javascript code and run it? Either in your browser or in a runtime like Node? I mean when you run it with HTML and CSS in the browser and try to console log something then you see your console logs in the browser, but when you write console logs in a runtime like Node then you see them in the terminal? &lt;/p&gt;

&lt;p&gt;Why there are some APIs that you can use while writing frontend like localStorage or Canvas but not while writing Backend using Nodejs, I mean both of them are using Javascript, right?&lt;/p&gt;

&lt;p&gt;Spoiler - It's because of the Javascript engine.&lt;/p&gt;

&lt;p&gt;So, today in this blog we are going to understand &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;what is a Javascript engine?&lt;/li&gt;
&lt;li&gt;What is its purpose?&lt;/li&gt;
&lt;li&gt;How does it work?&lt;/li&gt;
&lt;li&gt;How Javascript runs on both client-side and server-side&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  What is a Javascript Engine?
&lt;/h2&gt;

&lt;p&gt;So a Javascript engine is basically a piece of code that is used to convert Javascript code into machine-understandable code and execute it.&lt;br&gt;
There are many Javascript engines available in different browsers for example - &lt;br&gt;
Chrome - V8 Engine&lt;br&gt;
Mozilla - SpiderMonkey&lt;br&gt;
Safari - JavaScriptCore&lt;br&gt;
... and many more&lt;/p&gt;

&lt;p&gt;Let's understand the workings of the Javascript engine by taking the V8 engine as the base.&lt;/p&gt;

&lt;p&gt;So we know that computers only understand binary i.e. 0's and 1's right? So we have to follow some steps before our computer can understand our code written in JS just like any other language.&lt;/p&gt;

&lt;p&gt;So there are multiple steps before the source code written by a Developer is ready to be machine understandable. Let's go to each step and understand what's happening there.&lt;/p&gt;

&lt;h2&gt;
  
  
  Tokenization
&lt;/h2&gt;

&lt;p&gt;When you write JavaScript code, the first step in the journey from source code to executable instructions is tokenization.&lt;/p&gt;

&lt;p&gt;Tokenization, also known as lexical analysis, involves breaking down the source code into smaller units called tokens. &lt;br&gt;
Tokens are the building blocks of a programming language and represent individual elements such as keywords, identifiers, operators, and literals.&lt;/p&gt;

&lt;p&gt;Here is an example - &lt;br&gt;
&lt;code&gt;let x = 10 + 5;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Its tokenized form will look like - "let", "x", "=", "10", "+", "5", ";"&lt;/p&gt;

&lt;p&gt;Once the given code is tokenized then the parser converts that code into an AST (Abstract Syntax Tree)&lt;/p&gt;

&lt;p&gt;The AST (Abstract Syntax Tree) is like a map of your code's structure.&lt;/p&gt;

&lt;p&gt;Imagine your code as a story. The AST breaks down this story into smaller pieces, like sentences and paragraphs, called nodes. Each node represents different parts of your code, like statements, expressions, or functions.&lt;br&gt;
Semantic Analysis is like checking the grammar and meaning of your story.&lt;/p&gt;

&lt;p&gt;Once we have the map (AST), we want to make sure the story makes sense. Semantic analysis is like checking the grammar and meaning of the words and sentences. It helps us catch mistakes and makes sure the story follows the rules of the language it's written in.&lt;br&gt;
So, in simpler terms, the AST helps us understand the structure of the code, and semantic analysis makes sure the code is well-written and follows the rules. It's like having a guide to understand the layout of your code and a proofreader to check if your code "speaks" correctly.&lt;/p&gt;

&lt;p&gt;So once the AST is ready the next step that comes into play is generation of bytecode.&lt;/p&gt;

&lt;h2&gt;
  
  
  Bytecode
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwschv7yq0px6o90g8gsy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwschv7yq0px6o90g8gsy.png" alt="Bytecode" width="800" height="536"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So what is this byte code? Bytecode is an abstraction of machine code. Bytecode is what makes Javascript run on all platforms like Windows, Android, MacOS, etc. Bytecode is created keeping the system architecture in which it is being executed in check. What does this mean?&lt;/p&gt;

&lt;p&gt;So whenever we download an application on our PC, there are mostly 2 versions available for that software one is for 64-bit architecture and the other for 32-bit architecture right? But why this is done? This is done because languages like C++ are compiled languages, which means that the whole code is compiled first and then an execution file is created which runs your code. So the executable file that is created after the compilation is only that machine's architecture specific. Meaning it is only optimized for that architecture. That's why most software has two versions of the same software.&lt;/p&gt;

&lt;p&gt;But we never had this problem in opening a website on any system right? We just type in the site of the name and voilà it opens up.&lt;/p&gt;

&lt;p&gt;This is because Javascript is platform independent, and what makes it platform independent? &lt;strong&gt;Bytecode&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Bytecode is generated in the JIT (Just in Time) compilation.&lt;/p&gt;

&lt;p&gt;So if I have to give a short analogy&lt;/p&gt;

&lt;p&gt;Bytecode is like a translator who knows all the languages (meaning different architectures) and it helps the JIT (tourist) understand the place where it is (Different platforms), but the translator is always the tourist's same friend, just that it knows a lot of languages.&lt;/p&gt;

&lt;p&gt;(If you don't understand JIT yet don't worry I'll explain it as well)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bytecode as a Translator:&lt;/strong&gt;&lt;br&gt;
Bytecode acts as an intermediate representation or a translator that is knowledgeable about different architectures or platforms. It is designed to be platform-independent, like a translator who understands various languages.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;JIT Compiler as a Tourist:&lt;/strong&gt;&lt;br&gt;
The JIT compiler is a tourist who wants to explore a new place (execute code on a specific device or architecture). The tourist, or JIT compiler, relies on the translator (bytecode) to guide and communicate with the locals (native machine code) effectively.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Portability of Bytecode:&lt;/strong&gt;&lt;br&gt;
The translator (bytecode) is versatile and can assist the tourist (JIT compiler) in any location, making the code portable across different architectures. The tourist doesn't need to learn every local language; instead, they communicate through the translator.&lt;/p&gt;

&lt;h2&gt;
  
  
  JIT compilation
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm5vi29rcugnn0wamq37q.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm5vi29rcugnn0wamq37q.jpg" alt="venndiagram" width="800" height="437"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Compilation? Compiler? So Javascript is a compiled language? &lt;strong&gt;No it's not&lt;/strong&gt;, So is it interpreted language? Haha &lt;strong&gt;No&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Javascript is a "Just-In-Time (JIT) compiled" language, what does that even mean?&lt;/p&gt;

&lt;p&gt;So we know how compiled languages and interpreted languages work right?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Compiled Languages&lt;/strong&gt;&lt;br&gt;
A compiled language will take the whole source and convert it to machine code at once and will return an executable file. During this phase user can do nothing but wait.&lt;/p&gt;

&lt;p&gt;Slower Start-Up Time - So the startup time is slow because it is reading the whole source code at once, but the later executions are fast as the machine code is already created in the exe file and we can just run it.&lt;/p&gt;

&lt;p&gt;Platform Dependency: The compiled code is often platform-specific, requiring different binaries for different architectures.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interpreted Language&lt;/strong&gt;&lt;br&gt;
An Interpreted language will read the code line by line and execute it line by line.&lt;/p&gt;

&lt;p&gt;Slower Execution: Interpreted code tends to run slower than compiled code since the interpreter must translate each line of code on the fly.&lt;br&gt;
No Static Optimization: Interpreters cannot perform extensive static optimizations before execution.&lt;/p&gt;

&lt;p&gt;JIT takes the best of both worlds. How?&lt;br&gt;
JIT is comprised of both a compiler and an interpreter, so what happens is when JS code first comes in contact with the JS engine, it starts with the interpreter, Why? So that the execution can get started and the user does not need to wait. It starts to run the code. &lt;/p&gt;

&lt;p&gt;While it is running the code it also keeps track of what functions or parts of code are being called again and again and marks them as hot paths. Once enough data is collected to call a function a &lt;strong&gt;hot path&lt;/strong&gt;, the compiler kicks in and takes the byte code and creates a more optimized version of that bytecode, and caches it.&lt;/p&gt;

&lt;p&gt;So the next time when the same function is called again, the interpreter does not reads it again, but the compiler sends the pre-compiled code and is executed directly. &lt;/p&gt;

&lt;p&gt;There is also a system of fallback in the compiler, so if there are some changes detected in the cached function or code, then that cache is not used and the interpreter re-executes the code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What are these changes that are detected?&lt;/strong&gt;&lt;br&gt;
So you know how sometimes we have a function that takes in a value, now lets say when the hot path was created till then an integer value was being passed in that function, but now suddenly a string is passed into that function, this causes in the change of bytecode as the data type is changed and hence the same optimized bytecode cannot be used. This is also why it is advised to keep type safety in your code and not change it again and again because JIT won't be able to create optimized byte code otherwise.&lt;/p&gt;

&lt;p&gt;In the V8 engine, the interpreter is known as &lt;strong&gt;ignition&lt;/strong&gt;, the Compiler is known as &lt;strong&gt;TurboFan&lt;/strong&gt; and the system that tracks the hot paths is called &lt;strong&gt;profiler&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Here is a diagram which explains the above process&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2br31r0pn0jgphlw0y4y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2br31r0pn0jgphlw0y4y.png" alt="JS engine working" width="800" height="483"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now that we understand what is the purpose of the JS engine and how it works, there is just one thing left, how does JS run on servers? Like Node.js?&lt;/p&gt;

&lt;p&gt;So Node.js acts as a wrapper around V8, providing additional features and modules for server-side development.&lt;/p&gt;

&lt;p&gt;Node.js provides an additional layer of functionality and modules on top of the V8 engine to enable server-side development. &lt;/p&gt;

&lt;p&gt;Node.js includes its own event loop, which is responsible for managing asynchronous operations. This event loop allows Node.js to efficiently handle multiple concurrent connections without blocking the execution of code.&lt;/p&gt;

&lt;p&gt;The wrapper provides abstractions for working with non-blocking I/O operations, making it easier for developers to write asynchronous code.&lt;/p&gt;

&lt;p&gt;Node.js includes a set of built-in modules and APIs for common server-side tasks, such as file system operations, networking, HTTP handling, and more.&lt;br&gt;
These built-in modules, like fs for file system operations and HTTP for creating HTTP servers, are part of the wrapper that Node.js provides.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Here is a summary of what we understood today&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;JavaScript Engine Fundamentals:&lt;/strong&gt;&lt;br&gt;
A JavaScript engine, such as V8, serves as the powerhouse behind code execution, translating JavaScript code into machine-readable instructions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Browser Environment:&lt;/strong&gt;&lt;br&gt;
In the browser, JavaScript interacts with APIs provided by the browser environment, including the DOM API, Web APIs, and more. This enables dynamic and interactive web pages.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Node.js on the Server:&lt;/strong&gt;&lt;br&gt;
Node.js acts as a wrapper around the V8 engine on the server side, extending JavaScript capabilities for server-side development. It introduces features like event-driven architecture, a CommonJS module system, and built-in APIs for server tasks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Compilation Process:&lt;/strong&gt;&lt;br&gt;
The journey from source code to execution involves tokenization, AST creation, and semantic analysis. The Abstract Syntax Tree acts as a map, guiding the understanding of code structure.&lt;br&gt;
Bytecode and JIT Compilation:&lt;/p&gt;

&lt;p&gt;Bytecode serves as an intermediate representation, making JavaScript platform-independent. JIT compilation optimizes hot paths dynamically, combining the benefits of both compiled and interpreted languages.&lt;/p&gt;

&lt;p&gt;Thanks for reading this far😁.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>What is the Internet?</title>
      <dc:creator>Samyak Jain</dc:creator>
      <pubDate>Fri, 29 Dec 2023 07:12:46 +0000</pubDate>
      <link>https://dev.to/samyak112/what-is-the-internet-part-1-4804</link>
      <guid>https://dev.to/samyak112/what-is-the-internet-part-1-4804</guid>
      <description>&lt;p&gt;The Internet is something that everyone knows about these days from any adult to any 2nd grader, it's such a common thing that we use every day, and yet know so less about it at least I was unaware of a lot of things regarding the internet&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;What are its origins? &lt;/li&gt;
&lt;li&gt;Where does it come from? &lt;/li&gt;
&lt;li&gt;Is it Tangible? &lt;/li&gt;
&lt;li&gt;How does my phone send data wirelessly using the Internet? &lt;/li&gt;
&lt;li&gt;How is it traveling through thin air?&lt;/li&gt;
&lt;li&gt;How does the Internet reach me? &lt;/li&gt;
&lt;li&gt;How does my ISP help me in that?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These are some questions out of a long list of questions I had regarding the internet. So, through this blog, I will try to answer those questions and hope to clear at least some common doubts people have regarding it.&lt;/p&gt;

&lt;p&gt;This is going to be a long blog because I am going to try to explain every aspect of it in detail. &lt;/p&gt;

&lt;p&gt;Here is a list of topics covered in this blog:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Origins of Internet&lt;/li&gt;
&lt;li&gt;NCP&lt;/li&gt;
&lt;li&gt;Transition to TCP/IP architecture&lt;/li&gt;
&lt;li&gt;IP Addressing&lt;/li&gt;
&lt;li&gt;Classful addressing scheme&lt;/li&gt;
&lt;li&gt;Local Host&lt;/li&gt;
&lt;li&gt;Subnetting&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Origins of Internet
&lt;/h2&gt;

&lt;p&gt;I think the origin of the internet is the best topic to start with when understanding what the internet is.&lt;br&gt;
So, the origins of the Internet can be traced back to the 1960s when the United States Department of Defense initiated a research project called &lt;strong&gt;ARPANET&lt;/strong&gt;. So yeah earlier, the first name of the Internet as we know it today was &lt;strong&gt;ARPANET&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So What was Used before ARPANET was introduced? What problem did ARPANET Solve?&lt;/p&gt;

&lt;p&gt;So Before ARPANET, communication networks were often centralized, meaning there was a single point of control or a small number of central hubs.&lt;br&gt;
In a centralized system, if a central point failed or was targeted, then the entire network could become disrupted.&lt;/p&gt;

&lt;p&gt;ARPANET laid the foundation for the development of a decentralized and distributed network architecture.&lt;/p&gt;

&lt;p&gt;ARPANET adopted a decentralized architecture where communication was distributed across multiple nodes (computers) rather than relying on a single central authority. Each node had a level of autonomy, and data could take multiple paths to reach its destination. This decentralized approach made the network more resilient and adaptable to failures.&lt;/p&gt;

&lt;p&gt;ARPANET implemented packet-switching, a method in which data is broken down into smaller packets before transmission. Each packet could take different routes to reach its destination, where it would be reassembled. &lt;/p&gt;

&lt;p&gt;During the time of ARPANET, the protocol which was used for transferring data was 'NCP' &lt;/p&gt;

&lt;p&gt;If I have to explain how NCP and ARPANET used to work together then I'll say Imagine ARPANET as a large postal system designed to connect different regions and facilitate the exchange of letters between individuals and organizations.&lt;/p&gt;

&lt;p&gt;Now, imagine that NCP is like a standardized letter format and a set of protocols that ensure proper formatting, addressing, and delivery of letters within the postal system.&lt;/p&gt;

&lt;p&gt;NCP provides the rules and conventions for how letters (data) should be packaged, addressed, and transmitted over the ARPANET. It specifies how to break down a long letter into manageable pieces (packets) and how to reassemble them at the destination.&lt;/p&gt;

&lt;h2&gt;
  
  
  NCP (Network control protocol)
&lt;/h2&gt;

&lt;p&gt;The primary purpose of NCP was to facilitate communication between computers on the ARPANET. It provided a basic mechanism for sending and receiving messages between different hosts connected to the network. &lt;br&gt;
Sounds something like another protocol that we use these days right? TCP/IP?&lt;/p&gt;

&lt;p&gt;So if we already had a protocol that was used for communication then why did we transition to the TCP/IP architecture?&lt;/p&gt;

&lt;h2&gt;
  
  
  Transition to TCP/IP architecture
&lt;/h2&gt;

&lt;p&gt;Although NCP was working at that time there were many flaws in it.&lt;br&gt;
I will explain one problem at a time and then the solution introduced by the TCP/IP architecture of that problem.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Scalability Issues in Uniquely Identifying Devices&lt;/strong&gt;&lt;br&gt;
So NCP was also uniquely identifying devices but it used a flat addressing structure. Let's try to understand this with an analogy.&lt;/p&gt;

&lt;p&gt;Imagine a city without a well-organized addressing system. In this city, each building has a unique address, but there's no logical or hierarchical structure to how the addresses are assigned. For instance:&lt;/p&gt;

&lt;p&gt;Building 1 might be on Elm Street.&lt;br&gt;
Building 2 could be on Maple Avenue.&lt;br&gt;
Building 3 might be on Oak Lane.&lt;/p&gt;

&lt;p&gt;Now, think of these addresses as the host addresses in the context of NCP. Each host on the ARPANET had a unique identifier, but these identifiers didn't follow a structured or hierarchical pattern.&lt;/p&gt;

&lt;p&gt;As the city grows, new buildings and streets are added. Allocating addresses becomes a challenge because there's no efficient way to organize them. With no hierarchy, the city's post office has to maintain an exhaustive list of every address, and it becomes increasingly difficult to manage as the city expands.&lt;/p&gt;

&lt;h2&gt;
  
  
  IP Addressing
&lt;/h2&gt;

&lt;p&gt;IP (Internet Protocol) suggested a Hierarchical structure instead of Flat Structure&lt;/p&gt;

&lt;p&gt;Let's see an Analogy of that too -&lt;/p&gt;

&lt;p&gt;Imagine that the city adopts a new addressing system inspired by ZIP codes. In this system:&lt;/p&gt;

&lt;p&gt;ZIP Code 10000 represents a large district or neighborhood.&lt;br&gt;
ZIP Code 10010 might represent a smaller area within that district.&lt;br&gt;
ZIP Code 10011 could pinpoint an even more specific location.&lt;/p&gt;

&lt;p&gt;In the world of IP, think of the ZIP codes as the network portion of the IP address. The hierarchy allows for efficient allocation and routing&lt;/p&gt;

&lt;p&gt;Currently, there are two versions of IP i.e IPv4 and IPv6 we will talk about IPv4 for now and will later come back to talk about IPv6&lt;/p&gt;

&lt;p&gt;The idea was initially as we discussed to remove the need for a flat structure and have a hierarchal structure so the addresses are well organized. But it was not achieved instantly IP address also evolved.&lt;/p&gt;

&lt;p&gt;So When IP was first introduced it was a 32-bit addressing scheme, &lt;br&gt;
In this scheme, the 32-bit IP address was divided into two parts&lt;br&gt;
Network Portion and the Host Portion, in this division the Network Portion had 1 Octet (8 Bits) and the rest were for hosts.&lt;/p&gt;

&lt;p&gt;Now because only 8 Bits were reserved for the Network Portion, it meant that only 256 networks were possible (2 raise to the power 8)&lt;/p&gt;

&lt;p&gt;But it was soon realized that 256 networks alone won't be enough, many small networks would be willing to join the &lt;strong&gt;ARPANET&lt;/strong&gt; and it will be a waste to allocate such a big number of hosts in just 256 unique networks&lt;/p&gt;

&lt;h2&gt;
  
  
  Classful addressing scheme
&lt;/h2&gt;

&lt;p&gt;To Overcome this issue Classful addressing scheme was introduced.&lt;br&gt;
In the scheme, IP addresses were divided into classes to allocate address space based on the size of the network.&lt;/p&gt;

&lt;p&gt;Basically, all we have is a 32-bit IP address in IPv4, which makes approximately 4.3 billion, now it's up to us how we use it efficiently. (In the Ipv4 version)&lt;/p&gt;

&lt;p&gt;That's where Classful addressing came in, Classful addressing suggested that instead of just making 256 networks because of the previous architecture, let's divide the IP address according to use cases this way, we can allocate an approximate amount to the people according to their need&lt;/p&gt;

&lt;p&gt;There were three primary classes:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Class A (1.0.0.0 to 126.0.0.0):&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In Class A first octet or the first 8 bits were allocated for the network and the rest were allocated for hosts. Out of the first Octet, the first bit was fixed as &lt;strong&gt;0&lt;/strong&gt;, which was an Identifier for Class A addresses.&lt;br&gt;
The remaining 7 Bits were used to create networks so there were 128 networks available and each network had approximately 16 million hosts.&lt;/p&gt;

&lt;p&gt;There are 2 fewer networks available overall since IP Address 0.0.0.0 is set aside for broadcasting needs. &lt;/p&gt;

&lt;p&gt;For usage as a loopback address while testing software, the IP address 127.0.0.1 is set aside. (Our good old LocalHost)&lt;/p&gt;

&lt;p&gt;Let's talk a bit about this special use case of LocalHost&lt;/p&gt;

&lt;h2&gt;
  
  
  Local Host 127.0.0.1
&lt;/h2&gt;

&lt;p&gt;So the loopback address 127.0.0.1 (localhost) is a reserved IP address used for testing and development. &lt;/p&gt;

&lt;p&gt;So when a request is sent using the localhost address, it is sent to your own device as if it came from somewhere else. &lt;/p&gt;

&lt;p&gt;The operating system's network stack recognizes the loopback address as a special case and ensures that the data doesn't leave the device's network interface.&lt;/p&gt;

&lt;p&gt;While 127.0.0.1 is the most commonly used loopback address, the entire range 127.0.0.0 to 127.255.255.255 is reserved for loopback purposes. Other addresses within this range (e.g., 127.0.0.2, 127.0.0.3) can also be used for testing multiple loopback interfaces.&lt;/p&gt;

&lt;p&gt;So when you write localhost:3000 you are actually hitting 127.0.0.1:3000, the term &lt;strong&gt;localhost&lt;/strong&gt; actually works as a domain name to map 127.0.0.1, we will talk more about this mapping when we talk about DNS (Domain Name System).&lt;/p&gt;

&lt;p&gt;While talking about localhosts there is one more component that is added in the localhost which is a port number like &lt;strong&gt;3000&lt;/strong&gt;, why is this port number added?&lt;/p&gt;

&lt;p&gt;This port number is added to an IP address to identify multiple services going on, on one machine which is identified by an IP address.&lt;/p&gt;

&lt;p&gt;If you have worked with both the backend and frontend, you must have seen that your frontend may run on localhost:5173 and your backend may run on localhost:3000, this helps the network to understand where exactly to send the information.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Now back to the discussion of classful addressing&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Class B (128.0.0.0 to 191.255.0.0):&lt;/strong&gt;&lt;br&gt;
The first two octets identify the network, and the remaining two octets represent hosts.&lt;/p&gt;

&lt;p&gt;If we talk about the first two octets, the first two bits are reserved to identify class B which is &lt;strong&gt;10&lt;/strong&gt;. The remaining are used for networks. So in class B, there are approximately 16,384&lt;br&gt;
where each network can accommodate 165,534 hosts.&lt;/p&gt;

&lt;p&gt;If you are not clear how I got the number 165,534 , then here is the math.&lt;br&gt;
We used the first two bits to reserve the identifier of class B and we were left with 14 bits which makes up for 16,384 networks (2 raised to the power 14)&lt;/p&gt;

&lt;p&gt;Now we are left with 2 more octets which were left for hosts allotment, so &lt;strong&gt;2^16 - 2 = 165, 534&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here 2 are reserved addresses&lt;br&gt;
Suited for medium-sized networks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Class C (192.0.0.0 to 223.255.255.0):&lt;/strong&gt;&lt;br&gt;
The first three octets identify the network, and the last octet represents the hosts.&lt;br&gt;
In this, the first 3 bits represent Class C which is &lt;strong&gt;110&lt;/strong&gt; and the rest represents the networks so approximately 2,097,152 networks and hosts (254)&lt;br&gt;
Designed for smaller networks.&lt;/p&gt;

&lt;p&gt;Seems interesting right? But many problems arose over time in this scheming.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Inefficient Use of Address Space - If you are a company and am assuming a very large company and you got assigned a Class A network, will you actually need  16 million hosts? This resulted in a lot of wastage of this exhaustible resource of IP addresses.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The allocation of entire Class B address blocks to medium-sized organizations, even if they didn't need a large number of addresses, contributed to a phenomenon known as the "Class B explosion." This led to a significant increase in the number of entries in the global routing table of the routers.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Management - Another problem was that it was not easy to administer such a big network even if I talk about a class B network it still has like 65 thousand networks.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;To solve the management problem, people thought to divide those networks into sub-networks so that they are easy to maintain this is what we call subnetting.&lt;/p&gt;

&lt;h2&gt;
  
  
  Subnetting
&lt;/h2&gt;

&lt;p&gt;Now before we go and understand subnet let's first again understand how it actually helps in maintaining IP addresses.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Customized Configurations - Let's say your company has multiple departments like finance, development, sales, etc. Now, consider a scenario where the finance team should have access to a private database containing financial information about the company, which is hosted in the company's private network. However, the company does not want every department to have access to that database. This is where subnetting comes into play. Using subnetting, you divide your company's IP address space into multiple sub-networks or subnets. In the configuration of your private database, you set up access controls to allow only the specific subnet associated with the finance department to access that database.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Decentralized System - With subnetting the network is somewhat decentralized, so if there is some problem in one subnet, it won't affect the whole system, and hence helps you to easily pinpoint where the error or bug has originated from.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Easy Monitoring - Subnets make the monitoring more organized and easy to track, if I want to know how much traffic is there in one department (subnet) or how much data is being shared in one subnet I can easily filter.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now that we know the &lt;strong&gt;why&lt;/strong&gt; let's talk about the &lt;strong&gt;What&lt;/strong&gt; and &lt;strong&gt;how&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is a Subnet&lt;/strong&gt;&lt;br&gt;
Let's extend our city analogy to incorporate subnetting:&lt;/p&gt;

&lt;p&gt;Original City Blocks (Networks):&lt;br&gt;
Downtown (Network Portion): Addresses starting with "100" represent the Downtown area.&lt;/p&gt;

&lt;p&gt;Uptown (Network Portion): Addresses starting with "200" represent the Uptown area.&lt;/p&gt;

&lt;p&gt;Suburbs (Network Portion): Addresses starting with "300" represent the suburbs.&lt;/p&gt;

&lt;p&gt;Subnetting within Neighborhoods:&lt;br&gt;
Now, imagine that each neighborhood decides to further organize itself into smaller blocks or zones for specific purposes.&lt;/p&gt;

&lt;p&gt;Downtown (Network Portion 100):&lt;/p&gt;

&lt;p&gt;Block A (Subnet): Addresses within the range "100.1" to "100.50" are designated for residential use.&lt;br&gt;
Block B (Subnet): Addresses within the range "100.51" to "100.100" are allocated for businesses.&lt;br&gt;
Uptown (Network Portion 200):&lt;/p&gt;

&lt;p&gt;Block X (Subnet): Addresses within the range "200.1" to "200.30" are for schools.&lt;br&gt;
Block Y (Subnet): Addresses within the range "200.31" to "200.60" are for parks.&lt;/p&gt;

&lt;p&gt;So what does a subnet look like? Well, the subnet is a 32-bit address that is present alongside an IP address, It is used to identify the devices that are present on the same subnet (I know a little confusing, but bear with me), So how a subnet is identified? &lt;/p&gt;

&lt;p&gt;So a subnet is divided between the network portion and the host portion, The network portion is uneditable, but on the other side host portion tells us how many hosts are available in that subnet.&lt;/p&gt;

&lt;p&gt;So again, what does a subnet look like? Here is an example of a subnet - &lt;code&gt;255.255.255.0&lt;/code&gt; (Subnet of a Class C network).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Now why the number 255? Why not any other number?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So in a subnet mask, continuous 1 bits represent the network portion and the continuous 0 bits represent the host portion, so if you convert the &lt;code&gt;255.255.255.0&lt;/code&gt; to a binary representation, it will look something like this &lt;code&gt;11111111.11111111.11111111.00000000&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;So if you look at the first octet (The first 8 bits) you will see its 11111111, and if you convert it to decimal representation it will be &lt;strong&gt;255&lt;/strong&gt;. So that's it, that's why a 255 represents a full octet or the network portion, I like to think of it like this because the octet contains all 1s then there are no more possible combinations left and that's the best way to show that it's uneditable.&lt;/p&gt;

&lt;p&gt;Now 255 in an octet alone won't make sense, for example, 0.255.255.0 can't be called a subnet mask. Why? Because the subnet needs to be a contiguous stream of 0s and 1s you can't start 0s and then suddenly 1s and then back to 0s.&lt;/p&gt;

&lt;p&gt;let me show this in binary representation -&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Given Subnet Mask - 255.255.255.0
Binary -  11111111.11111111.11111111.00000000&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This will be a subnet because first there are continuous, 1s, and then 0s, and yes on the left side , it should always be 1s and on the right side 0s.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Given Subent Mask - 255.207.255.0
Binary - 11111111.11001111.11111111.00000000&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This can't be called a subnet, why? because it's not contiguous, we did start with continuous 1s but then in the middle, it started to have 0s and then again 1s.&lt;/p&gt;

&lt;p&gt;Now that we have understood the &lt;strong&gt;What&lt;/strong&gt; let's understand the &lt;strong&gt;how&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How does subnetting work in a network of subnets?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let's say I have a Class C Network and because in Classful addressing you get the whole network then I'll assume my IP address is 192.168.1.0 so the range will be 192.168.1.0 to 192.168.1.255.&lt;/p&gt;

&lt;p&gt;Now in classful addressing you have to keep the same size for all of your subnets, so if your finance team has more people than the sales team, you will have to make the same host size subnet for the sales team as well because the finance team has more people.&lt;/p&gt;

&lt;p&gt;So let's say I want to make 4 subnets of my network.&lt;/p&gt;

&lt;p&gt;Now am using a Class C network whose default subnet mask is &lt;code&gt;255.255.255.0&lt;/code&gt;, so if I want to have subnets in my network then my subnet will look like this - &lt;code&gt;255.255.255.192&lt;/code&gt;.&lt;br&gt;
Why?&lt;/p&gt;

&lt;p&gt;Let's look at the binary representation of &lt;code&gt;255.255.255.0&lt;/code&gt; &lt;br&gt;
Binary - &lt;code&gt;11111111.11111111.11111111.00000000&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Here I can see that I have 8 bits in the network portion so if I want to make space for 4 subnets then I'll have to reserve 2 bits in the given 8bits of 0s, which gives us (2 raise to the power of 2) 4 subnets, and hence our subnet mask will look like &lt;code&gt;11111111.11111111.11111111.11000000&lt;/code&gt; - &lt;code&gt;255.255.255.192&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This left us with 6 bits, so 2 raises to the power 6 gives us 64 hosts per subnet.&lt;/p&gt;

&lt;p&gt;So this gives us the following range of addresses taking &lt;code&gt;192.168.1.0&lt;/code&gt; as the base address-&lt;/p&gt;

&lt;p&gt;Subnet 1: &lt;code&gt;192.168.1.0&lt;/code&gt; to &lt;code&gt;192.168.1.63&lt;/code&gt;&lt;br&gt;
Subnet 2: &lt;code&gt;192.168.1.64&lt;/code&gt; to &lt;code&gt;192.168.1.127&lt;/code&gt;&lt;br&gt;
Subnet 3: &lt;code&gt;192.168.1.128&lt;/code&gt; to &lt;code&gt;192.168.1.191&lt;/code&gt;&lt;br&gt;
Subnet 4: &lt;code&gt;192.168.1.192&lt;/code&gt; to &lt;code&gt;192.168.1.255&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now how does communication work between these subnets? &lt;br&gt;
So a router works as a gateway between subnets, it contains the subnet mask and the reserved gateway IP address, so when a request is made from a device of a subnet, let's say device A makes a request to device B on the same subnet, so the request will go through router first.&lt;/p&gt;

&lt;p&gt;The router will see hmmm, this request came from Device A who wants to send this to some Device B. The router checks the IP Address of Device B which is sent by Device A, and checks if it in the same subnet. How does a router do that? Because it already has the subnet mask of that subnet. If it is in the same subnet it routes the information to that device otherwise routes the information to another router. Now how does the router find which router it needs to send it to? That is another big topic and should be kept seperately I suppose.&lt;/p&gt;

&lt;p&gt;Now we have only covered Classful addressing in this blog, in the next blog we will talk about Classless Inter-Domain Routing, remember this is only 1 reason why we shifted from NCP to TCP/IP architecture, once this is completed we will go to the next reason.&lt;/p&gt;

&lt;p&gt;Thanks for reading this far 😁&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>learning</category>
      <category>softwaredevelopment</category>
    </item>
  </channel>
</rss>
