<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Eric Leung - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Eric Leung - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 15 May 2026 17:23:12 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/erictleung/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ 10 to the Power of 0: the Zero Exponent Rule and the Power of Zero Explained ]]>
                </title>
                <description>
                    <![CDATA[ Exponents are important in the financial world, in scientific notation, and in the fields of epidemiology and public health. So what are they, and how do they work? Exponents are written like (3^2) or (10^3). But what happens when you raise a number ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/10-to-the-power-of-0-the-zero-exponent-rule-and-the-power-of-zero-explained/</link>
                <guid isPermaLink="false">66d45e3cd7a4e35e3843495d</guid>
                
                    <category>
                        <![CDATA[ Math ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Mathematics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MathJax ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Eric Leung ]]>
                </dc:creator>
                <pubDate>Tue, 26 Jan 2021 16:34:45 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/01/pexels-katerina-holmes-5905857.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Exponents are important in the financial world, in scientific notation, and in the fields of epidemiology and public health. So what are they, and how do they work?</p>
<p>Exponents are written like (3^2) or (10^3).</p>
<p>But what happens when you raise a number to the (0) power like this?</p>
<p>$$10^0 = \text{?}$$</p><p>This article will go over</p>
<ul>
<li><p>the basics of exponents,</p>
</li>
<li><p>what they mean, and</p>
</li>
<li><p>it will show that (10^0) equals (1) using negative exponents</p>
</li>
</ul>
<p>All I'm assuming is that you have an understanding of multiplication and division.</p>
<h2 id="heading-exponents-are-made-up-of-a-base-and-exponent-or-power">Exponents are made up of a base and exponent (or power)</h2>
<p>First, let's start with the parts of an exponent.</p>
<p>There are two parts to an exponent:</p>
<ol>
<li><p>the base</p>
</li>
<li><p>the exponent or power</p>
</li>
</ol>
<p>At the beginning, we had an exponent (3^2). The "3" here is the <strong>base</strong>, while the "2" is <strong>the exponent or power</strong>.</p>
<p>We read this as</p>
<blockquote>
<p>Three is raised to the power of two.</p>
</blockquote>
<p>or</p>
<blockquote>
<p>Three to the power of two.</p>
</blockquote>
<p>More generally, exponents are written as (a^b), where (a) and (b) can be any pair of numbers.</p>
<h2 id="heading-exponents-are-multiplication-for-the-lazy">Exponents are multiplication for the "lazy"</h2>
<p>Now that we have some understanding of how to talk about exponents, how do we find what number it equals?</p>
<p>Using our example from above, we can write out and expand "three to the power of two" as</p>
<p>$$3^2 = 3 \times 3 = 9$$</p><p>The left-most number in the exponent is the number we are multiplying over and over again. That is why you are seeing multiple 3's. The right-most number in the exponent is the number of multiplications we do. So for our example, the number 3 (the base) is multiplied two times (the exponent).</p>
<p>Some more examples of exponents are:</p>
<p>$$10^3 = 10 \times 10 \times 10 = 1000$$</p><p>$$2^{10} = 2 \times 2 \times 2 \times 2 \times 2 \times 2 \times 2 \times 2 \times 2 \times 2 = 1024$$</p><p>More generally, we can write these exponents as</p>
<p>$$\textcolor{orange}{b}^\textcolor{blue}{n} = \underbrace{\textcolor{orange}{b} \times \dots \times \textcolor{orange}{b}}_{\textcolor{blue}{n} \textrm{ times}}$$</p><p>where, the (\textcolor{orange}{\text{letter <code>b'' is the base}}\) we are multiplying over and over again and the \(\textcolor{blue}{\text{letter</code> n'' is power}}) or (\textcolor{blue}{\text{exponent}}), which is the number of times we are multiplying the base by itself.</p>
<p>For these examples above, the exponent values are relatively small. But you can imagine if the powers are very large, it becomes redundant to keep writing the numbers over and over again using multiplication signs.</p>
<p><strong>In sum, exponents help make writing these long multiplications more efficient.</strong></p>
<h2 id="heading-numbers-to-the-power-of-zero-are-equal-to-one">Numbers to the power of zero are equal to one</h2>
<p>The previous examples show powers of greater than one, but what happens when it is zero?</p>
<p>The quick answer is that any number, (b), to the power of zero is equal to one.</p>
<p>$$b^0 = 1$$</p><p>Based on our previous definitions, we just need zero of the base value. Here, let's have our base number be 10.</p>
<p>$$10^0 = ? = 1$$</p><p>But what does a "zero" number of base numbers mean? Why does this happen?</p>
<p><strong>We can figure this out by dividing multiple times to decrease the power value until we get to zero.</strong></p>
<p>Let's start with</p>
<p>$$10^3 = 10 \times 10 \times 10 = 1000$$</p><p>To decrease the powers, we need to briefly understand the concepts of</p>
<ul>
<li><p>combining exponents</p>
</li>
<li><p>powers of one</p>
</li>
</ul>
<p>In our quest to decrease the exponent from (10^3) ("ten to the third power") to (10^0) ("ten to the zeroth power"), we will keep on doing the opposite of multiplying, which is dividing.</p>
<p>$$\frac{10^3}{10} = \frac{10 \times 10 \times 10}{10} = \frac{1000}{10} = 100$$</p><p>The right-most parts of this will probably make sense. But how do we write exponents when we have (10^3) divided by (10)?</p>
<h3 id="heading-how-powers-of-one-work">How powers of one work</h3>
<p>First, any (\textcolor{orange}{\text{exponents with powers of one}}) are equal to just (\textcolor{blue}{\text{the base number}}).</p>
<p>$$\textcolor{orange}{b^1} = \textcolor{blue}{b}$$</p><p>There is only one value being "multiplied" so we are getting the value itself.</p>
<p>We need this "power of one" definition so we can rewrite the fraction with exponents.</p>
<p>$$\frac{10^3}{10} = \frac{10^3}{10^1}$$</p><h3 id="heading-how-to-decrease-exponents-to-zero">How to decrease exponents to zero</h3>
<p>As a reminder, one way to figure out how (10^0) is equal to 1 is to keep on dividing by 10 until we get to an exponent of zero.</p>
<p>We know from the right side of the equation above we should get 100 from (\frac{10^3}{10^1}).</p>
<p>$$\frac{10^3}{10} = \frac{10^3}{10^1} = \frac{10 \times 10 \times 10}{10^1}$$</p><p>Before we finish dividing by one 10, we can multiply the top and bottom by 1 as placeholders when we cancel numbers out.</p>
<p>$$\frac{10 \times 10 \times 10}{10^1} = \frac{10 \times 10 \times 10 \times 1}{10^1 \times 1} = \frac{10 \times 10 \times \cancel{10} \times 1}{\cancel{10^1} \times 1} = \frac{10 \times 10 \times 1}{1}$$</p><p>From this, we can see we get 100 again.</p>
<p>$$\frac{10 \times 10 \times 1}{1} = \frac{10 \times 10}{1} = \frac{10^2}{1} = \frac{100}{1}$$</p><p>We can divide by 10 two more times to finally get to (10^0).</p>
<p>$$\frac{10^2 \times 1}{10 \times 10 \times 1} = \frac{\cancel{10} \times \cancel{10} \times 1}{\cancel{10} \times \cancel{10} \times 1} = \frac{10^0 \times 1}{1} = \frac{1}{1} = 1$$</p><p>Because we divided by two 10's when we only had two 10's in the top of the fraction, we have zero tens in the top. Having zero tens pretty much means we get (10^0).</p>
<h3 id="heading-how-negative-exponents-work">How negative exponents work</h3>
<p>Now, the (10^0) kind of comes out of nowhere, so let's explore this some more using "negative exponents".</p>
<p>More generally, this repetitive dividing by the same base is the same as multiplying by "negative exponents".</p>
<p>A negative exponent is a way to rewrite division.</p>
<p>$$\frac{1}{\textcolor{purple}{b^n}}= \textcolor{green}{b^{-n}}$$</p><p>A (\textcolor{green}{\text{negative exponent}}) can be re-written as a fraction with the denominator (or the bottom of a fraction) with the (\textcolor{purple}{\text{same exponent but with a positive power}}) (the left side of this equation).</p>
<p>Now, using negative exponents, we can show the previous division in another way.</p>
<p>$$\frac{10^2 \times 1}{10 \times 10 \times 1} = \frac{10^2}{10^2} = 10^2 \times \frac{1}{10^2} = 10^2 \times 10^{-2}$$</p><p><strong>Note</strong>, one rule of exponents is that when you multiply exponents with the same base number (remember, our base number here is 10), you can add the exponents.</p>
<p>$$10^2 \times 10^{-2} = 10^{2 + (-2)} = 10^{2 - 2} = 10^{0}$$</p><h3 id="heading-putting-it-together">Putting it together</h3>
<p>Knowing this, we can combine each of these equations above to summarize our result.</p>
<p>$$\textcolor{purple}{\frac{10^2}{10^2}} = 10^2 \times 10^{-2} = 10^{2 + (-2)} = 10^{2 - 2} = \textcolor{blue}{10^{0}} \textcolor{orange}{= 1}$$</p><p>We know that (\textcolor{purple}{\text{dividing a number by itself}}) will (\textcolor{orange}{\text{equal to one}}). And we've shown that (\textcolor{purple}{\text{dividing a number by itself}}) also equals (\textcolor{blue}{\text{ten to the zero power}}). Math says that things that are equal to the same thing are also equal to each other.</p>
<p>Thus, (\textcolor{blue}{\text{ten to the zero power}}) is (\textcolor{orange}{\text{equal to one}}). This exercise above generalizes to any base number, <strong>so any number to the power of zero is equal to one.</strong></p>
<h2 id="heading-in-summary">In summary</h2>
<p>Exponents are convenient ways to do repetitive multiplication.</p>
<p>Generally, exponents follow this pattern below, with some (\textcolor{orange}{\text{base number}}) being multiplied over and over again (\textcolor{blue}{\text{``n'' number of times}}).</p>
<p>$$\textcolor{orange}{b}^\textcolor{blue}{n} = \underbrace{\textcolor{orange}{b} \times \dots \times \textcolor{orange}{b}}_{\textcolor{blue}{n} \textrm{ times}}$$</p><p>Using negative exponents, we can take what we know from multiplication and division (like for the fraction 10 over 10,(\frac{10}{10})) to show that (b^0) is equal to one for any number (b) (like (10^0 = 1)).</p>
<p>Follow me on <a target="_blank" href="https://twitter.com/erictleung">Twitter</a> and check out my <a target="_blank" href="https://erictleung.com">personal blog</a> where I share some other insights and helpful resources for programming, statistics, and machine learning.</p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is a Correlation Coefficient? The r Value in Statistics Explained ]]>
                </title>
                <description>
                    <![CDATA[ Correlations are a great tool for learning about how one thing changes with another. After reading this, you should understand what correlation is, how to think about correlations in your own work, and code up a minimal implementation to calculate co... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-a-correlation-coefficient-r-value-in-statistics-explains/</link>
                <guid isPermaLink="false">66d45e3e47a8245f78752a2e</guid>
                
                    <category>
                        <![CDATA[ Mathematics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MathJax ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Eric Leung ]]>
                </dc:creator>
                <pubDate>Wed, 08 Jul 2020 12:00:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/07/positive_plots.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Correlations are a great tool for learning about how one thing changes with another. After reading this, you should understand what correlation is, how to think about correlations in your own work, and code up a minimal implementation to calculate correlations.</p>
<h2 id="heading-a-correlation-is-about-how-two-things-change-with-each-other">A correlation is about how two things change with each other</h2>
<p>Correlation is an abstract math concept, but you probably already have an idea about what it means. Here are some examples of the three general categories of correlation.</p>
<p>As you eat more food, you will probably end up feeling more full. This is a case of when two things are changing together in the same way. One goes up (eating more food), then the other also goes up (feeling full). <strong>This is a positive correlation</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/07/pos_plot.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Positive correlation between food eaten and feeling full. More food is eaten, the more full you might feel (trend to the top right).</em> <a target="_blank" href="https://gist.github.com/erictleung/d6bda6a61b8de03e76cb081257f183ee"><em>R code</em></a></p>
<p>When you're in a car and it goes faster, you will probably get to your destination faster and your total travel time will be less. This is a case of two things changing in the opposite direction (more speed, but less time). <strong>This is a negative correlation</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/07/neg_plot.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Negative correlation between car speed and travel time. The faster the car, less travel time (trend to the bottom right).</em> <a target="_blank" href="https://gist.github.com/erictleung/d6bda6a61b8de03e76cb081257f183ee"><em>R code</em></a></p>
<p>There is also a third possible way two things can "change". Or rather, not change. For example, if you were to gain weight and looked at how your test scores changed, there probably won't be any general pattern of change in your test scores. <strong>This means there's no correlation.</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/07/non_plot.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>An exaggerated plot of no correlation between weight gain and test scores.</em> <a target="_blank" href="https://gist.github.com/erictleung/d6bda6a61b8de03e76cb081257f183ee"><em>R code</em></a></p>
<h2 id="heading-knowing-about-how-two-things-change-together-is-the-first-step-to-prediction">Knowing about how two things change together is the first step to prediction</h2>
<p>Being able to describe what is going on in our previous examples is great and all. But what's the point? The reason is to apply this knowledge in a meaningful way to help predict what will happen next.</p>
<p>In our eating example, we may record how much we eat for a whole week and then make a note of how full we feel afterwards. As we found before, the more we eat, the more full we feel.</p>
<p>After collecting all of this information, we can ask more questions about why this happens to better understand this relationship. Here, we may start to ask what kind of foods make us more full, or whether the time of day affects how full we feel as well.</p>
<p>Similar thinking can be applied to your job or business as well. If you notice sales or other important metrics are going up or down with other measure of your business (in other words, things are positively correlated or negatively correlated), it may be worth exploring and learning more about that relationship to improve your business.</p>
<h2 id="heading-correlations-can-have-different-levels-of-strength">Correlations can have different levels of strength</h2>
<p>We've covered some general correlations as either</p>
<ul>
<li><p>positive,</p>
</li>
<li><p>negative, or</p>
</li>
<li><p>non-existent</p>
</li>
</ul>
<p>Although those descriptions are okay, all positive and negative correlations are not all the same.</p>
<p>These descriptions can also be translated to numbers. A correlation value can take on any decimal value between negative one, (-1), and positive one, (+1).</p>
<p>Decimal values between (-1) and (0) are negative correlations, like (-0.32).</p>
<p>Decimal values between (0) and (+1) are positive correlations, like (+0.63).</p>
<p>A perfect zero correlation means there is no correlation.</p>
<p>For each type of correlation, there is a range of strong correlations and weak correlations. Correlation values <strong>closer to zero are weaker correlations</strong>, while values <strong>closer to positive or negative one are stronger correlation</strong>.</p>
<p>Strong correlations show more obvious trends in the data, while weak ones look messier. For example, the stronger high, positive correlation below looks more like a line compared to the weaker and lower, positive correlation.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/positive_plots-1.png" alt="Examples of low, high, and perfect positive correlations between x and y" width="600" height="400" loading="lazy"></p>
<p><em>Varying levels of positive correlations.</em> <a target="_blank" href="https://gist.github.com/erictleung/d6bda6a61b8de03e76cb081257f183ee"><em>R code</em></a><em>.</em></p>
<p>Similarly, strongly negative correlations have a more obvious trend than the weaker and lower negative correlation.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/07/negative_plots-2.png" alt="Examples of low, high, and perfect negative correlations between x and y" width="600" height="400" loading="lazy"></p>
<p><em>Varying levels of negative correlations.</em> <a target="_blank" href="https://gist.github.com/erictleung/d6bda6a61b8de03e76cb081257f183ee"><em>R code</em></a></p>
<h2 id="heading-where-does-the-r-value-come-from-and-what-values-can-it-take">Where does the <em>r</em> value come from? And what values can it take?</h2>
<p>The "<em>r</em> value" is a common way to indicate a correlation value. More specifically, it refers to the (sample) Pearson correlation, or Pearson's <em>r</em>. The "sample" note is to emphasize that you can only claim the correlation for the data you have, and you must be cautious in making larger claims beyond your data.</p>
<p>The table below summarizes what we've covered about correlations so far.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Pearson's r value</td><td>Correlation between two things is...</td><td>Example</td></tr>
</thead>
<tbody>
<tr>
<td>r = -1</td><td>Perfectly negative</td><td>Hour of the day and number of hours left in the day</td></tr>
<tr>
<td>r &lt; 0</td><td>Negative</td><td>Faster car speeds and lower travel time</td></tr>
<tr>
<td>r = 0</td><td>Independent or uncorrelated</td><td>Weight gain and test scores</td></tr>
<tr>
<td>r &gt; 0</td><td>Positive</td><td>More food eaten and feeling more full</td></tr>
<tr>
<td>r = 1</td><td>Perfectly positive</td><td>Increase in my age and increase in your age</td></tr>
</tbody>
</table>
</div><p>In the next few sections, we will</p>
<ul>
<li><p>Break down the math equation to calculate correlations</p>
</li>
<li><p>Use example numbers to use this correlation equation</p>
</li>
<li><p>Code up the math equation in Python and JavaScript</p>
</li>
</ul>
<h2 id="heading-breaking-down-the-math-to-calculate-correlations">Breaking down the math to calculate correlations</h2>
<p>As a reminder, correlations can only be between (-1) and (1). Why is that?</p>
<p>The quick answer is that we adjust the amount of change in both variables to a common scale. In more technical terms, we normalize how much the two variables change together by how much each of the two variables change by themselves.</p>
<p>From <a target="_blank" href="https://en.wikipedia.org/wiki/Correlation_and_dependence#Sample_correlation_coefficient">Wikipedia</a>, we can grab the math definition of the Pearson correlation coefficient. It looks very complicated, but let's break it down together.</p>
<p>$$\textcolor{lime}{r} { \textcolor{#4466ff}{x} \textcolor{fuchsia}{y} } = \frac{ \sum{i=1}^{n} (x_i - \textcolor{green}{\bar{x}})(y_i - \textcolor{olive}{\bar{y}}) }{ \sqrt{ \sum_{i=1}^{n} (x_i - \textcolor{green}{\bar{x}})^2 \sum_{i=1}^{n} (y_i - \textcolor{olive}{\bar{y}})^2 } }$$</p><p>From this equation, to find the (\textcolor{lime}{\text{correlation}}) between an ( \textcolor{#4466ff}{\text{x variable}} ) and a ( \textcolor{fuchsia}{\text{y variable}} ), we first need to calculate the ( \textcolor{green}{\text{average value for all the } x \text{ values}} ) and the ( \textcolor{olive}{ \text{average value for all the } y \text{ values}} ).</p>
<p>Let's focus on the top of the equation, also known as the numerator. For each of the ( x) and (y) variables, we'll then need to find the distance of the (x) values from the average of (x), and do the same subtraction with (y).</p>
<p>Intuitively, comparing all these values to the average gives us a target point to see how much change there is in one of the variables.</p>
<p>This is seen in the math form, (\textcolor{#800080}{\sum_{i=1}^{n}}(\textcolor{#000080}{x_i - \overline{x}})), (\textcolor{#800080}{\text{adds up all}}) the (\textcolor{#000080}{\text{differences between}}) your values with the average value for your (x) variable.</p>
<p>In the bottom of the equation, also known as the denominator, we do a similar calculation. However, before we add up all of the distances from our values and their averages, we will multiple them by themselves (that's what the ((\ldots)^2) is doing).</p>
<p>This denominator is what "adjusts" the correlation so that the values are between (-1) and (1).</p>
<h2 id="heading-using-numbers-in-our-equation-to-make-it-real">Using numbers in our equation to make it real</h2>
<p>To demonstrate the math, let's find the correlation between the ages of you and your siblings last year ([1, 2, 6]) and your ages for this year ([2, 3, 7]). Note that this is a small example. Typically you would want many more than three samples to have more confidence in your correlation being true.</p>
<p>Looking at the numbers, they appear to increase the same. You may also notice they are the same sequence of numbers but the second set of numbers has one added to it. This is as close to a perfect correlation as we'll get. In other words, we should get an (r = 1).</p>
<p>First we need to calculate the averages of each. The average of ([1, 2, 6]) is ((1+2+6)/3 = 3) and the average of ([2, 3, 7]) is ((2+3+7)/3 = 4). Filling in our equation, we get</p>
<p>$$r { x y } = \frac{ \sum{i=1}^{n} (x_i - 3)(y_i - 4) }{ \sqrt{ \sum_{i=1}^{n} (x_i - 3)^2 \sum_{i=1}^{n} (y_i - 4)^2 } }$$</p><p>Looking at the top of the equation, we need to find the paired differences of (x) and (y). Remember, the (\sum) is the symbol for adding. The top then just becomes</p>
<p>$$(1-3)(2-4) + (2-3)(3-4) + (6-3)(7-4)$$</p><p>$$= (-2)(-2) + (-1)(-1) + (3)(3)$$</p><p>$$= 4 + 1 + 9 = 14$$</p><p>So the top becomes 14.</p>
<p>$$r { x y } = \frac{ 14 }{ \sqrt{ \sum{i=1}^{n} (x_i - 3)^2 \sum_{i=1}^{n} (y_i - 4)^2 } }$$</p><p>In the bottom of the equation, we need to do some very similar calculations, except focusing on just the (x) and (x) separately before multiplying.</p>
<p>Let's focus on just ( \sum_{i=1}^n (x_i - 3)^2 ) first. Remember, (3) here is the average of all the (x) values. This number will change depending on your particular data.</p>
<p>$$(1-3)^2 + (2-3)^2 + (6-3)^2$$</p><p>$$= (-2)^2 + (-1)^2 + (3)^2 = 4 + 1 + 9 = 14$$</p><p>And now for the (y) values.</p>
<p>$$(2-4)^2 + (3-4)^2 + (7-4)^2$$</p><p>$$(-2)^2 + (-1)^2 + (3)^2 = 4 + 1 + 9 = 14$$</p><p>We those numbers filled out, we can put them back in our equation and solve for our correlation.</p>
<p>$$r _{ x y } = \frac{ 14 }{ \sqrt{ 14 \times 14 }} = \frac{14}{\sqrt{ 14^2}} = \frac{14}{14} = 1$$</p><p>We've successfully confirmed that we get (r = 1).</p>
<p>Although this was a simple example, it is always best to use simple examples for demonstration purposes. It shows our equation does indeed work, which will be important when coding it up in the next section.</p>
<h2 id="heading-python-and-javascript-code-for-the-pearson-correlation-coefficient">Python and JavaScript code for the Pearson correlation coefficient</h2>
<p>Math can sometimes be too abstract, so let's code this up for you to experiment with. As a reminder, here is the equation we are going to code up.</p>
<p>$$r { x y } = \frac{ \sum{i=1}^{n} (x_i - \bar{x})(y_i - \bar{y}) }{ \sqrt{ \sum_{i=1}^{n} (x_i - \bar{x})^2 \sum_{i=1}^{n} (y_i - \bar{y})^2 } }$$</p><p>After going through the math above and reading the code below, it should be a bit clearer on how everything works together.</p>
<p>Below is the Python version of the Pearson correlation.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> math


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">pearson</span>(<span class="hljs-params">x, y</span>):</span>
    <span class="hljs-string">"""
    Calculate Pearson correlation coefficent of arrays of equal length.
    Numerator is sum of the multiplication of (x - x_avg) and (y - y_avg).
    Denominator is the squart root of the product between the sum of 
    (x - x_avg)^2 and the sum of (y - y_avg)^2.
    """</span>
    n = len(x)
    idx = range(n)

    <span class="hljs-comment"># Averages</span>
    avg_x = sum(x) / n
    avg_y = sum(y) / n

    numerator = sum([(x[i] - avg_x)*(y[i] - avg_y) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> idx])

    denom_x = sum([(x[i] - avg_x)**<span class="hljs-number">2</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> idx])
    denom_y = sum([(y[i] - avg_y)**<span class="hljs-number">2</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> idx])
    denominator = math.sqrt(denom_x * denom_y)

    <span class="hljs-keyword">return</span> numerator / denominator
</code></pre>
<p>Here's an example of our Python code at work, and we can double check our work using <a target="_blank" href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html">a Pearson correlation function</a> from the SciPy package.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">import</span> scipy.stats

<span class="hljs-comment"># Create fake data</span>
x = np.arange(<span class="hljs-number">5</span>, <span class="hljs-number">15</span>)  <span class="hljs-comment"># array([ 5,  6,  7,  8,  9, 10, 11, 12, 13, 14])</span>
y = np.array([<span class="hljs-number">24</span>, <span class="hljs-number">0</span>, <span class="hljs-number">58</span>, <span class="hljs-number">26</span>, <span class="hljs-number">82</span>, <span class="hljs-number">89</span>, <span class="hljs-number">90</span>, <span class="hljs-number">90</span>, <span class="hljs-number">36</span>, <span class="hljs-number">56</span>])

<span class="hljs-comment"># Use a package to calculate Pearson's r</span>
<span class="hljs-comment"># Note: the p variable below is the p-value for the Pearson's r. This tests</span>
<span class="hljs-comment">#   how far away our correlation is from zero and has a trend.</span>
r, p = scipy.stats.pearsonr(x, y)
r  <span class="hljs-comment"># 0.506862548805646</span>

<span class="hljs-comment"># Use our own function</span>
pearson(x, y)  <span class="hljs-comment"># 0.506862548805646</span>
</code></pre>
<p>Below is the JavaScript version of the Pearson correlation.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">pearson</span>(<span class="hljs-params">x, y</span>) </span>{
    <span class="hljs-keyword">let</span> n = x.length;
    <span class="hljs-keyword">let</span> idx = <span class="hljs-built_in">Array</span>.from({<span class="hljs-attr">length</span>: n}, <span class="hljs-function">(<span class="hljs-params">x, i</span>) =&gt;</span> i);

    <span class="hljs-comment">// Averages</span>
    <span class="hljs-keyword">let</span> avgX = x.reduce(<span class="hljs-function">(<span class="hljs-params">a,b</span>) =&gt;</span> a + b) / n;
    <span class="hljs-keyword">let</span> avgY = y.reduce(<span class="hljs-function">(<span class="hljs-params">a,b</span>) =&gt;</span> a + b) / n;

    <span class="hljs-keyword">let</span> numMult = idx.map(<span class="hljs-function"><span class="hljs-params">i</span> =&gt;</span> (x[i] - avg_x)*(y[i] - avg_y));
    <span class="hljs-keyword">let</span> numerator = numMult.reduce(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b);

    <span class="hljs-keyword">let</span> denomX = idx.map(<span class="hljs-function"><span class="hljs-params">i</span> =&gt;</span> <span class="hljs-built_in">Math</span>.pow((x[i] - avgX), <span class="hljs-number">2</span>)).reduce(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b);
    <span class="hljs-keyword">let</span> denomY = idx.map(<span class="hljs-function"><span class="hljs-params">i</span> =&gt;</span> <span class="hljs-built_in">Math</span>.pow((y[i] - avgY), <span class="hljs-number">2</span>)).reduce(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b);
    <span class="hljs-keyword">let</span> denominator = <span class="hljs-built_in">Math</span>.sqrt(denomX * denomY);

    <span class="hljs-keyword">return</span> numerator / denominator;
};
</code></pre>
<p>Here's an example of our JavaScript code at work to double check our work.</p>
<pre><code class="lang-javascript">x = <span class="hljs-built_in">Array</span>.from({<span class="hljs-attr">length</span>: <span class="hljs-number">10</span>}, <span class="hljs-function">(<span class="hljs-params">x, i</span>) =&gt;</span> i + <span class="hljs-number">5</span>)
<span class="hljs-comment">// Array(10) [ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]</span>

y = [<span class="hljs-number">24</span>, <span class="hljs-number">0</span>, <span class="hljs-number">58</span>, <span class="hljs-number">26</span>, <span class="hljs-number">82</span>, <span class="hljs-number">89</span>, <span class="hljs-number">90</span>, <span class="hljs-number">90</span>, <span class="hljs-number">36</span>, <span class="hljs-number">56</span>]

pearson(x, y)
<span class="hljs-comment">// 0.506862548805646</span>
</code></pre>
<p>Feel free to translate the formula into either Python or JavaScript to better understand how it works.</p>
<h2 id="heading-in-conclusion">In conclusion</h2>
<p>Correlations are a helpful and accessible tool to better understand the relationship between any two numerical measures. It can be thought of as a start for predictive problems or just better understanding your business.</p>
<p>Correlation values, most commonly used as Pearson's <em>r</em>, range from (-1) to (+1) and can be categorized into negative correlation ((-1 \lt r \lt 0)), positive ((0 \lt r \lt 1)), and no correlation ((r = 0)).</p>
<h2 id="heading-a-glimpse-into-the-larger-world-of-correlations">A glimpse into the larger world of correlations</h2>
<p>There is more than one way to calculate a correlation. Here we have touched on the case where both variables change at the same way. There are other cases where one variable may change at a different rate, but still have a clear relationship. This gives rise to what's called, <a target="_blank" href="https://www.freecodecamp.org/news/how-machines-make-predictions-finding-correlations-in-complex-data-dfd9f0d87889/">non-linear relationships</a>.</p>
<p>Note, <a target="_blank" href="https://www.freecodecamp.org/news/why-correlation-does-not-imply-causation-the-meaning-of-this-common-saying-in-statistics/">correlation does not imply causation</a>. If you need quick examples of why, <a target="_blank" href="http://tylervigen.com/spurious-correlations">look no further</a>.</p>
<p>Below is a list of other articles I came across that helped me better understand the correlation coefficient.</p>
<ul>
<li><p>If you want to explore a great interactive visualization on correlation, take a look at <a target="_blank" href="https://rpsychologist.com/d3/correlation/">this simple and fantastic</a> site.</p>
</li>
<li><p>Using Python, there multiple ways to implement a correlation and there are multiple types of correlation. This <a target="_blank" href="https://realpython.com/numpy-scipy-pandas-correlation-python/">excellent tutorial</a> shows great examples of Python code to experiment with yourself.</p>
</li>
<li><p>A <a target="_blank" href="https://sebastiansauer.github.io/correlation-intuition/">blog post by Sabatian Sauer</a> goes over correlations using "average deviation rectangles", where each point creates a visual rectangle from each point using the mean, and illustrating it using the R programming language.</p>
</li>
<li><p>And for the deeply curious people out there, take a look at <a target="_blank" href="http://www.stat.berkeley.edu/~rabbee/correlation.pdf">this paper showing 13 ways to look at the correlation coefficient</a> (PDF).</p>
</li>
</ul>
<p>Follow me on <a target="_blank" href="https://twitter.com/erictleung">Twitter</a> and check out my <a target="_blank" href="https://erictleung.com">personal blog</a> where I share some other insights and helpful resources for programming, statistics, and machine learning.</p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
