Showing posts with label mathematics. Show all posts
Showing posts with label mathematics. Show all posts

Probability Distribution Example [w/ the NYC Tree Census]

Probability distributions take samples from a population, calculating the proportions of a certain item within each sample in order to estimate the parameter proportion. The parameter proportion is defined to be the actual proportion within the sample. The sample size of the amount of samples you take from the population for each collection of items (for your estimate) has a significant impact on your ability to predict the proportion. This can be demonstrated with a simple computer simulation.

London Planetree. Source

According to the 2015 NYC Tree Census, the most popular tree is the London planetree with 87014 member out of a total of 683788 total individual trees. This means our true parameter is 12.7%. In order to better estimate the figure from our proportion distribution, we will need to essentially make sure our probability distribution is normal.


This is accomplished via the normality test which states that: n*p >= 10 && n*(1-p) >= 10

where n is the sample size and p is the true proportion (parameter). If you aren't sure what p is, you will eventually reach a normal curve by increasing the sample size and re-running your simulation. You will also want to make sure that you are drawing samples from the same population each time you draw a sample (maintaining independence).

This principle is at work in the following example with the London planetrees:

Proportion of the London Planetree in the 2015 NYC Tree Census (n=5)

Since 5*.127 is not greater than ten, this simulation produces a graph that lacks normality.

Proportion of London Planetree in the 2015 NYC Tree Census (n=20)

Although 20*.127 is still not greater than ten, this simulation produces a graph that is closer to normal and less skewed than the previous example. This indicates that we are closer to achieving to our goal as we increase sample size. 

Proportion of London Planetree in the 2015 NYC Tree Census (n=200)

Since 200*.127>10, the condition for normality has been reached and we can form better estimates for the actual parameter proportion. 

Bonus Graphs (Sample Proportions for the 1995 and 2005 Census):

Proportion of London Planetree in the 2005 NYC Tree Census (n=200)

Proportion of London Planetree in the 1995 NYC Tree Census (n=200)
Feel free to remix the code with the three different datasets to try out these simulations for yourself (i.e. utilizing simulations for probability distributions).

Program Code


import pandas as pd
import matplotlib.pyplot as plt
from collections import Counter 
import numpy as np
from numpy.random import choice

def getKey(item):
    return item[1]

def main():
    treeStuff = pd.read_csv("new_york_tree_census_2015.csv")
    treeSpecies = list(treeStuff["spc_common"])
    treeSpeciesCombined = Counter(treeSpecies)
    j = sorted(treeSpeciesCombined.items(),key=getKey)
    treeSpecies2 = []
    treeCount = []
    for i in j:
        i = list(i)
        if (isinstance(i[0],float)):
            i[0] = "Unknown"
        treeSpecies2.append(i[0])
        treeCount.append(i[1])
    counts = []
    for k in range(0,1000):
        draw = choice(treeSpecies2, 200, p = [x / float(sum(treeCount)) for x in treeCount]) # where you set sample size
        count = sum(np.char.count(draw,sub="London planetree"))
        counts.append(count/float(len(draw)))
    probabilities = Counter(counts)
    l = sorted(probabilities.items())
    probCategories = []
    probValues = []
    for r in l:
        r = list(r)
        probCategories.append(r[0])
        probValues.append(r[1])
    x_pos = [e for e, _ in enumerate(probCategories)]
    plt.xticks(x_pos, probCategories,rotation='vertical')
    plt.xlabel("Proportion of London Planetree in a Sample")
    plt.ylabel("Number of Samples")
    plt.title("1000 Simple Random Sample's from 2015 NY Tree Census (n=200)")
    plt.bar(x_pos,probValues)
    plt.show()
    
main()

Data Source: See this file on Kaggle for the NYC Tree Census Data. 

How $\pi$ was almost $3.2$

Yes, you read that right. The numerical constant $\pi \approx 3.14$ could have been equal to $3.2$!

In 1894, physician and amateur mathematician Edward J. Goodwin (c.1825-1902) believed that he had found a way to square the circle. It was proven in 1882 that this can't be done by Ferdinand von Lindemann.

How did he do it then? The way he did it implied various wrong values of $\pi$, most commonly $3.2$. Here is an example. He made this diagram, which is a circle with diameter $10$. He then says the circumference is $32$, not $\sim 31.415...$, which means $\pi = 3.2$! However, at the time, $\pi$ was known to 527 correct digits.

He showed this to Indiana state representative Taylor I. Record, so schools could show this as a way to square the circle without royalties. Record then introduced it to the house under the excruciatingly long title "A Bill for an act introducing a new mathematical truth and offered as a contribution to education to be used only by the State of Indiana free of cost by paying any royalties whatever on the same, provided it is accepted and adopted by the official action of the Legislature of 1897". It was bill #246 of the 1897 sitting of the Indiana General Assembly.  

The bill somehow passed the Indiana House of Representatives, and was sent to the Indiana Senate. On the day they were going to vote, Professor Clarence Abiathar Waldo happened to be there. He explained to the Senate that the bill redefined $\pi$, and it actually almost passed, but one senator said that they had no power to define mathematical truth. That is why the Indiana Pi Bill did not pass.



Lemoine's Conjecture Verified to 10^10

The mathematician who first thought of this idea: Emile Lemoine
Lemoine's conjecture, sometimes referred to as Levy's conjecture, states that all odd numbers can be broken into the sum of an odd prime and an even semi-prime.

Here are three examples of "lemoine partitions", i.e. where the odd numbers are broken down into their constituent elements based on the definition above.
$$7 = 3 + 2 * 2$$
$$9 = 3 + 2 * 3$$
$$11 = 5 + 2 * 3$$
In 1999, Dann Corbit was able to verify the conjecture to 1,000,000,000 numbers utilizing the following code in C (https://groups.google.com/forum/?hl=en#!msg/sci.math/HoCpH8gPDHM/gtU-fuSWnFMJ):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define TEST( f, x ) ( *( f+( x )/16 )&( 1<<( ( ( x )%16L )/2 ) ) )
#define SET( f, x ) *( f+( x )/16 )|=1<<( ( ( x )%16L )/2 )

unsigned        ip(unsigned long j, unsigned char *d)
{
    if (j == 1)
        return 0;
    if ((j % 2) == 0) {
        if (j == 2)
            return 1;
        else
            return 0;
    } else
        return (!(*(d + (j) / 16) & (1 << (((j) % 16L) / 2))) && j != 1);
}

int             main(int argc, char *argv[])
{
    unsigned char  *feld = NULL,
    *zzz = NULL;
    unsigned long   teste = 1,
    max,
    mom,
    hits = 1,
    alloc;
    time_t          begin;
    unsigned char   quiet = 0;
    if (argc > 1) {
        max = atol(argv[1]) + 10000;
        if (argc > 2)
            quiet = 1;
    } else
        max = 1000000000L;
    
    zzz = feld = malloc(alloc = (((max -= 10000L) >> 4) + 1L));
    if (feld) {
        char            found;
        memset(zzz, 0, alloc);
        printf("Searching prime numbers to : %lu\n", max);
        begin = time(NULL);
        while ((teste += 2) < max)
            if (!TEST(feld, teste)) {
                ++hits;
                for (mom = 3L * teste; mom < max; mom += teste << 1)
                    SET(feld, mom);
            }
        printf(" %ld prime numbers found in %.2f secs.\n\n",
               hits, difftime(time(NULL), begin));
        {
            long            o,
            p,
            q,
            j;
            for (o = 7; o <= max; o += 2) {
                found = 0;
                for (j = 2; j < o;) {
                    p = j;
                    q = o - 2 * p;
                    if (ip(p, feld) && ip(q, feld)) {
                        if (!quiet)
                            printf("%lu = 2*%lu + %lu\n", o, p, q);
                        found = 1;
                        break;
                    }
                    if (j == 2)
                        j++;
                    else
                        j += 2;
                }
                if (!found)
                    printf("*** Problem!! %lu\n", o);
            }
            
            free(feld);
            printf(" Finished calculations in %.2f secs.\n\n",
                   difftime(time(NULL), begin));
        }
    } else {
        puts("Memory allocation failure.");
        exit(EXIT_FAILURE);
    }
    return 0;
}

A new verifier was implemented in Python to try and either match/exceed this number.

"""
Description: Traditional Implementation of Lemoine's Conjecture
"""

import numpy as np
import time

def primesfrom2to(n):
    # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    """ Input n>=6, Returns a array of primes, 2 <= p < n """
    sieve = np.ones(n/3 + (n%6==2), dtype=np.bool)
    sieve[0] = False
    for i in xrange(int(n**0.5)/3+1):
        if sieve[i]:
            k=3*i+1|1
            sieve[      ((k*k)/3)      ::2*k] = False
            sieve[(k*k+4*k-2*k*(i&1))/3::2*k] = False
    return np.r_[2,3,((3*np.nonzero(sieve)[0]+1)|1)]

def main():
    start_time = time.time()
    n = 7
    x = 0
    l = list(primesfrom2to(1000000000))
    sl = set(l)
    print("Done")
    print("--- %s seconds ---" % (time.time() - start_time))            

    while (n < 1000000000):
        if(n-(2*l[x]) in sl):
            n = n+2
            x = 0
        x = x + 1
    print("Done 2")  
    print("--- %s seconds ---" % (time.time() - start_time))            
    
main()

This version relied on a pre-generated list of prime numbers in both list and set form to generate odd numbers sequentially. It rearranges the formal definition of Odd # = 2q + p to Odd # - 2q = p to take advantage of python's native set data type and enhanced searching capabilities. Replacing these with just lists, numpy arrays, or iterators was considered but not successfully implemented in a time-conserving manner.

You can track the progress of the generator by inserting this code snippet within the if statement within the while loop within the main method.

if n % 1000 == 1:
                print("\r{}/{}".format(n, 100000))

Here is a table with the speed results from this implementation. The program reached 2*10^9 before stressing the hardware due to lack of available memory.

Odd #’s up to ___ checked
Time
10,000
--- 0.0129 seconds ---
100,000
--- 0.129 seconds ---
1,000,000
--- 1 seconds ---
10,000,000
--- 11 seconds ---
100,000,000
--- 138 seconds ---
1,000,000,000
--- 1593 seconds ---
2,000,000,000
--- 3,487 seconds ---

Another approach would be to generate the results from all of the combinations of p + 2q and match those up to a list of the odd numbers greater than or equal to seven. This was implemented with the following program.

"""
Description: New strategy to tackle verifying Lemoine's conjecture
"""

import numpy as np
import time
from operator import add

def primesfrom2to(n):
    # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    """ Input n>=6, Returns a array of primes, 2 <= p < n """
    sieve = np.ones(n/3 + (n%6==2), dtype=np.bool)
    sieve[0] = False
    for i in xrange(int(n**0.5)/3+1):
        if sieve[i]:
            k=3*i+1|1
            sieve[      ((k*k)/3)      ::2*k] = False
            sieve[(k*k+4*k-2*k*(i&1))/3::2*k] = False
    return np.r_[2,3,((3*np.nonzero(sieve)[0]+1)|1)]

def cartesian_add(arr1, arr2):
    arr1_e = np.repeat(np.expand_dims(arr1, 1), arr2.size, axis=1)
    arr2_e = np.repeat(np.expand_dims(arr2,  0), arr1.size, axis=0)
    return arr1_e + arr2_e

def main():
    start_time = time.time()
    list1 = primesfrom2to(1000000)
    list2 = 2 * list1
    list4 = np.arange(7,3000000,2)
    list4 = np.setdiff1d(list4,np.unique(cartesian_add(list1, list2)))
    print(list4)    
    print("--- %s seconds ---" % (time.time() - start_time))
  
main()

While the original versions of this implementation utilized nested for loops (later changed to for loop containing a map(add,primes,semiprimes) function with rolling numpy primes loop), Ernie Parke contributed the cartesian_add method which shaved off several seconds (it runs about 4x faster without the use of the np.unique function than the original implementation).

The cartesian_add function essentially generates all of the combinations of addition while the set.diff1d function figures out which numbers are only a part of the set of odd numbers (originally represented as list4) and therefore haven't been verified.
Schematic of the principle utilized in the "new strategy." Source
Nevertheless, this version was able to only check 100,000 numbers in approx. five seconds which was much slower when compared to the original implementation (see the table above).

Jacob G. of Futuresight Technologies also developed a C++ code to to verify Lemoine's conjecture for a certain number of digits. Please note that it requires -fopenmp flag if you want to utilize the parallelism within the program to decrease run-time.

#include <iostream>
#include <vector>
#include <set>

typedef unsigned long long ull;

using namespace std;

const ull maxNumber = 1000000000;

bool numberWorks(ull n, vector<ull>& primes, set<ull>& primeSet) {
    ull factor;
    ull remainder;
    ull primeSize = primes.size();
    ull semiPrime;
    for (ull i = 0; i < primeSize; i++) {
        factor = primes[i];
        if (factor > n) {
            return false;
        }
        remainder = n - factor;
        
        if (remainder % 2 == 0 && primeSet.find(remainder / 2) != primeSet.end()) {
            return true;
        }
    }
    return false;
}

int main() {
    bool* primes = new bool[maxNumber];
    bool* semiPrimes = new bool[maxNumber];
    
    vector<ull> primeList;
    set<ull> primeSet;
    
    for (int i = 0; i < maxNumber; i++) {
        primes[i] = true;
    }
    
    for (int i = 2; i < maxNumber; i++) {
        if (primes[i]) {
            for (int j = i; j < maxNumber; j += i) {
                primes[j] = false;
            }
            primeList.push_back(i);
            primeSet.insert(i);
        }
    }
    cout << "Computed primes!" << endl;
    
    #pragma omp parallel for num_threads(8)
    for (ull numberToCheck = 7; numberToCheck < maxNumber; numberToCheck += 2) {
        if (!numberWorks(numberToCheck, primeList, primeSet)) {
            cout << "Number failed: " << numberToCheck << endl;
        } else if ((numberToCheck - 1) % 1000000 == 0) {
            cout << (numberToCheck / (double)maxNumber) * 100 << "%" << endl;
        }
    }
    
    delete[] primes;
    delete[] semiPrimes;
}

He contributed the following speed readings:

Odd #’s up to ___ checked
Time
1,000,000
--- .6 seconds ---
10,000,000
--- 15 seconds ---
100,000,000
--- 301 seconds ---

Out of curiosity, the original C code was run again to see how efficient it was. Due to C being a compiled language, this test ended up being more successful than the python programs at and allowed the conjecture to be verified to 10^10 in a reasonable time period. Here are some times for those runs:

Odd #’s up to ___ checked
Time
1,000,000,000
--- 108 seconds ---
10,000,000,000
--- 1009 seconds ---

Therefore, it is concluded that the conjecture is now verified up to 10^10 through the original C code, and up to 2*10^9 through the new Python implementation.

Thank you to Ernie Parke and Jacob G. answering all of my questions throughout this process. 

Sources:
https://en.wikipedia.org/wiki/Lemoine%27s_conjecture
http://mathworld.wolfram.com/LevysConjecture.html
https://planetmath.org/levysconjecture
https://primes.utm.edu/curios/page.php?number_id=82&submitter=Capelle
https://www.mathsteacher.com.au/year7/ch11_ratios/04_prob/unit.htm
https://oeis.org/A046927

Numerical Methods: Estimating Integrals and the Trapezoidal Rule

The magnitude of an integral in 2D can be geometrically interpreted as the area bounded by y=f(x) and the x-axis between an interval. The positivity/negativity of the resulting integral is determined by how much area is over/under the x-axis such that any area over the x-axis adds to the value of the integral, and vice-versa. Thus, using basic geometry we are able to estimate/determine the value of an integral using common area formulas we already know, even integrals whose answer cannot be represented by elementary functions.

Many methods to estimate the area under a function evaluates the integral of simpler sub-curves that resembles the original function. Essentially, the curve is broken up into different sub-intervals and a simpler curve that estimates the original curve is created for each sub-interval. The curves made are generally a polynomial since polynomials are easy to integrate. Then, the integral of sub-curve in each sub-interval is evaluated and summed together. The result is an approximation of the integral of the entire curve.

Some notable and widely used methods include the Riemann sum which uses horizontal lines to estimate the integral, trapezoidal rule which use lines, and Simpson's 1/3 and 3/8 rule which uses degree two and three polynomials, respectively. It is important to note that estimating the integral of the overall curve then boils down to the integration of the sub-curves. If the area bounded by the sub-curve in each sub-interval and the x-axis is a simple shape (i.e. rectangles for the Riemann sum or polygons for the trapezoidal rule) then the integral of each sub-curve can be geometrically represented by such area.

Figure 1: The area under the curve in black is approximated using the (left) Riemann sum (in red), trapezoidal rule (in yellow) and the Simpson's 1/3 rule (in green). Note the number of sub-intervals in this case is two, and each different method uses different polymeric curves to resemble the shape of the original curve.
In figure 1 it is evident that the maximum error of the estimate decreases as we increase the degree of the polynomial used to estimate the curve. It is also the case that the larger the amount of sub-intervals, the smaller the maximum error. These properties are generally true for any function.

The Trapezoidal Rule

The trapezoidal rule is one of the easiest methods to estimate the value of an integral. It uses lines to approximate the shape of a curve. Then, the integration of all such lines results in an estimation. The trapezoidal rule is also simple to use since the equations are simple and the number of sub-intervals chosen do not have additional restrictions other than being positive (e.g. Simpson's 1/3 rule requires the number of sub-intervals to be even).

Figure 2: Graphical explanation of the trapezoidal rule: two sub-intervals $[x_0,x_1]$ and $[x_1,x_2]$ are created as $n=2$. A line is drawn from $f(x_0)$ to $f(x_1)$ and from $f(x_1)$ to $f(x_2)$. The sum of the integral of the lines (shaded in yellow) gives the estimated value of the function's integral. 

Derivation

We briefly discuss a geometric derivation of the trapezoidal rule. Suppose we have an integral that spans from $x_0=a$ to $x_n=b$. We assume the function is continuous over the interval. We can partition such interval $[a,b]$ into $n$ smaller sub-intervals such that $a = x_0 \lt x_1 \lt \dots \lt x_i \lt \dots \lt x_{n-1} \lt x_n=b$. Define $\Delta x_i$ to be $x_i - x_{i-1}$. Consider a sub-interval $[x_{i-1},x_i]$. The curve in the sub-interval is estimated to be a linear line between the bounds of the sub-interval evaluated at the function. If $f(x_i)$ and $f(x_{i-1}) \geq 0$ then the integral of the linear line is given by the area bounded by the line and x-axis in the interval. Thus, the integral and therefore the area in the subinterval is determined to be $$I_i \approx \frac{f(x_i)+f(x_{i-1})}{2}\Delta x_i \label{eq:1} \tag{1}$$
For $f(x_i)$ and $f(x_{i-1}) \leq 0$ the integral is estimated using the same method as above, and is the negative of the area. Thus it is $-\frac{|f(x_i)+f(x_{i-1})|}{2}\Delta x_i$. This equals to equation \ref{eq:1} since $f(x_i)$ and $f(x_{i-1}) \leq 0$. If $f(x_i)$ and $f(x_{i-1})$ have opposing signs, we can further break up the sub-interval. There only exists one point $x_k$ where $f(x_k)=0$ due to the intermediate value theorem and the fact that a line can only pass the x-axis once, never or an infinite amount of times. The estimated integral of the function in $[x_{i-1},x_i]$ is determined to be:
\begin{align*}I_i &\approx \frac{f(x_k)+f(x_{i-1})}{2}(x_k-x_{i-1})+\frac{f(x_i)+f(x_k)}{2}(x_i-x_k)\\
&=\frac{f(x_{i-1})}{2}(x_k-x_{i-1})+\frac{f(x_i)}{2}(x_i-x_k)\\\end{align*}By similar triangles we see that $x_k-x_{i-1}=-\frac{f(x_{i-1})\Delta x_i}{f(x_i)-f(x_{i-1})}$ and $x_i-x_k=\frac{f(x_i)\Delta x_i}{f(x_i)-f(x_{i-1})}$ so
\begin{align*}I_i &\approx -\frac{f^2(x_{i-1})}{2(f(x_i)-f(x_{i-1}))}\Delta x_i+\frac{f^2(x_i)}{2(f(x_i)-f(x_{i-1}))}\Delta x_i\\
&=\frac{f^2(x_i)-f^2(x_{i-1})}{2(f(x_i)-f(x_{i-1}))}\Delta x_i\\
&=\frac{f(x_i)+f(x_{i-1})}{2}\Delta x_i\\\end{align*}
Therefore regardless of the nature of the function in any sub-interval, the integral in $[x_{i-1},x_i]$ is estimated to be equation \ref{eq:1}.
The integral of the overall curve in the interval $[a,b]$ is the sum of all the estimated integrals in each sub-interval, explicitly:
$$I = \sum_{i=1}^{n} I_i$$
$$I \approx \sum_{i=1}^{n} \frac{f(x_{i-1})+f(x_{i})}{2}\Delta x_i \label{eq:2} \tag{2}$$

If the sub-intervals are evenly spaced, then
$$I \approx \frac{b-a}{2n}\sum_{i=1}^{n} \big(f(x_{i-1})+f(x_i)\big)$$
$$I \approx \frac{b-a}{2n} \bigg(f(x_0)+f(x_n)+2\sum_{i=1}^{n-1} f(x_{i})\bigg) \label{eq:3} \tag{3}$$

Equations \ref{eq:2} and \ref{eq:3} are the final forms used in this numerical method.


Implementation

Implementation of the trapezoidal rule is relatively straightforward. One thing to note is that the higher the number of sub-intervals, the better the accuracy however it is important to realize that the higher the number, the more prominent round-off errors get. Generally the round-off errors associated to this method are negligible assuming the number of intervals don't get ridiculously large. It is recommended to calculate and use the minimum number of sub-intervals to achieve a desired maximum error using this formula. Then as the integration bounds change, it is generally recommended to triple the number of sub-intervals for the doubling of the integration interval; this will keep the maximum error relatively the same assuming the maximum concavity of the function in the new interval change stays constant compared to the old one.
function f(x)
return math.sin(x)/x
end

a=1 --lower bound
b=3 --upper bound
n=5000 --number of sub-intervals

sum=0
for i=1,n do
xi=((b-a)*i/n)+a
xi1=((b-a)*(i-1)/n)+a
sum=sum+(f(xi)+f(xi1))*((b-a)/(2*n))
end

print(sum)
Figure 3: Lua code for the implementation of the trapezoidal rule. Note the estimation of a non-elementary integral sin(x)/x.

The method above is adequate but relies on the user to implement a suitable subinterval count. A better method of implementation involves estimating the integral with progressively more subintervals until the answer converges to a single value (i.e. is numerically stable). This is done by calculating the estimated integral while increasing the amount of subintervals used, calculating the relative difference between the current estimate with the previous best estimate as we go. Only when this error is below a preset tolerance will the answer be outputted. In the example below, this method is implemented in MATLAB but is improved with Romberg's method - a way to decrease the number of iterations used with the trapezoidal method.
rombInt(@(x) sin(x)./x,1,3)

function I=rombInt(f,a,b)
maxIter=1000; % Max iterations
etol = 1e-6; % Tolerance for relative error
n=1;
if a>=b
    error("Must provide unequal and smaller a value than b")
end
prev=Inf;
for j=1:maxIter
    % Apply trapezoidal rule twice for Romberg's method
    trap1=0;
    xDif=(b-a)/n;
    x=a:xDif:b;
    y=f(x);
    for i=1:length(x)-1
        trap1=trap1+0.5*(y(i)+y(i+1))*xDif;
    end
    n=n*2; % Double the trapezoidal rule subinterval count
    trap2=0;
    xDif=(b-a)/n;
    x=a:xDif:b;
    y=f(x);
    for i=1:length(x)-1
        trap2=trap2+0.5*(y(i)+y(i+1))*xDif;
    end
    n=n*2;
    % Calculate final integral
    I=(4/3)*trap2-(1/3)*trap1;
    if abs((prev-I)/I) <= etol
        fprintf("Convergence in %.d iterations",j)
        break
    elseif j==maxIter
        warning("Integral did not converge")
        break
    end
    prev=I;
end
end
Figure 4: MATLAB code for the implementation of an adaptive trapezoidal method.

Exercises

  1. Using the error formula for the trapezoidal rule what is the equation that gives the maximum possible error for trapezoidal estimation of $\int^{x}_{0} t^3+e^{t}~dt$ using $n$ equal sub-intervals? What is the formula for the exact error?
  2. Prove that the trapezoidal rule, for any number of sub-intervals greater or equal to 1,
    1. overestimates a parabola's integral if it faces upward.
    2. perfectly estimates the integral for functions of the form $y=ax+b$.
  3. Use the trapezoidal rule with $n=4$ to estimate $\int_{0}^{5}5x-5~dx$.
  4. Estimate the integral from $\pi$ to $2\pi$ of $\frac{\sin(x)}{x}$ with the minimum number of sub-intervals such that the maximum error is no more than 0.05.
  5. For batch/simple distillation where a binary liquid mixture is boiled and condensed into a receiving flask, the equation $\ln\Big(\frac{W}{F}\Big)=-\int_{x_w}^{x_f}\frac{dx}{y-x}$ is important to quantify the ending amounts of liquid in both containers and its respective concentrations. $x$ is related to $y$ as provided in the table below:
  6. Figure 5: Table of values for question 5.
    If $x_w=0.02, x_f=0.20$, and $F=1$, estimate $W$, the remaining liquid in the feed pot in mols. [1]
  7. Derive equation \ref{eq:1} using
    1. a geometric approach.
    2. a mathematical approach.
  8. Using one sub-interval with the trapezoidal rule to estimate certain functions is sometimes more accurate than using two or more intervals. Provide a function that shows this.
  9. Refer to Figure 1 and identify the numerical method that estimates the integral
    1. the most poorly?
    2. the most accurately?
    3. the quickest, if calculated manually?
    4. the slowest, if calculated manually?
  10. Refer to equation \ref{eq:3} and the equation directly above it. Why is it more efficient to use equation \ref{eq:3} rather than the other one, especially when manually evaluating the formula?
  11. We've seen different methods that can be used to estimate the integral of a curve. The ones mentioned use polynomials of varying degrees to resemble the shape of the original curve. Referring to Figure 5 and considering all the methods presented in this article, which method would be the best (efficiency and accuracy wise) at estimating the integral of the functions from $x=1$ to $x=5$? For each function,
    1. is equation \ref{eq:2} or \ref{eq:3} more useful?
    2. how many sub-intervals would you choose?
    3. where would you partition the sub-intervals?
Figure 6: Question 10 graphs - which method would be the best (efficiency and accuracy wise) at estimating the integral of the following functions?

[1] Question adapted from Prof. R. Pal from the University of Waterloo, Ontario.

Images belong to KrIsMa. HTML code format generated using hilite.me.

Regression to the Mean

Have you wondered why tall parents usually have smaller children, and vice versa? Galton discovered this and wondered why the children seemed so 'mediocre' than their parents. He then proceeded to coin this phenomenon 'regression towards mediocrity' [1].

Now named 'regression to the mean', this phenomenon is now considered an important factor to consider for valid research. When a variable that involves some randomness deviates significantly from a norm, regression to the mean states that it is likely a subsequent measurement will return a value that is closer to the expected norm.


Measurements 1 and 2 were taken from the same material and is represented by the red and blue lines, respectively.

This graph shows data for two measurements of a liquid and solid heterogeneous sample for its G'' values at different stresses. For each measurement, a minute amount of sample is taken from a container and placed into the measurement device. What is important is the massive fluctuations in the first measurement at low stresses is lessened and returns closer to its expected norm (represented by the gray dotted line) after the second measurement.

Why does this happen?

Heterogeneous mixtures can make taking a
 representative sample for testing more difficult.
Significant fluctuations from the norm can be caused by many factors such as human error, however regression to the mean is most applicable to non-systemic random errors. An example of such as error would be taking non-representative samples for testing (a sampling error). In order to get a certain measurement from a sample we need to collect a smaller representative sample from it to test. Random errors arise when taking such a sample, especially with heterogeneous mixtures. This is most likely the case for the example above; instead of taking a representative sample from this mixture in both measurements, it is likely that the sample taken from the container in measurement 1 was non-representative and contributed to unexpected deviations from the norm. Lastly, if we consider a common normal distribution we know that potential outlier values can result on rare occasions. Subsequent measurements are more likely to fall near the mean since it is more probable such values are to occur. This is actually one of the methods taken advantage of in p-hacking, where researchers purposely manipulate their research in a way that produces a rare and significant result that is often non-reproducible.




How it applies to research

Experimental research, where tests are conducted on two different experimental groups, allows researchers to accurately determine causal relationships between variables. If research was only done on one group of participants, regression to the mean would most likely produce favorable results for the researcher. Consider a clinical trial of a drug that is used to cure a disease. The researcher would gather a bunch of participants sick from such a disease, and allow the participants to take the drug. Regression to the mean would state that the most unhealthiest of the participants would likely get better as their health would get closer to the 'average human' - healthy. The researcher may then conclude that the drug is the cause of the participants getting better, but this is simply a case of regression to the mean. Testing on two representative groups - where one is given the drug in question and the other either a placebo or a competitor's drug, eliminates any biased conclusions that are based off regression to the mean.

As another example, research was done on if praise or punishment was better for pilots in terms of their quality of flight landings. When pilots made a landing which was better than average, they were praised. If they made a particularly bad landing, they were punished. Since regression of the mean states that in either case it is likely the pilot will subsequently return to a more 'average' landing quality, it was incorrectly concluded that punishment is more effective as a teaching tool than praise, since punished pilots whose previous bad landing was out of the norm improved on subsequent landings [2].


An example of the landing quality score of the pilots versus their landing number. Regression of the mean played a big part in the research performed to identify the effectiveness of praise vs. punishment for pilots as shown in this image.

Is regression to the mean applicable to everyday life?

Of course! Have you ever tried searching for a perfect online webpage to do some work (be it a good online grammar checker, plagiarism checker, useful SEO tool, etc.) and stumbled on a horribly made one out of the norm? If you're randomly trying to find another webpage, you're likely to click on a better webpage than the one before. This assumes that the indexing of the webpages involves some randomness which there is. It also assumes that the search engine isn't choosing to showing all horrible online webpages for you.

Interested in stock prices and finance? Mean reversion is based off of regression to the mean and states that sudden surges in stock prices will eventually die down and return back to the long-term average. This is based off the assumption that the short term price surge does not attract much attention media-wise and isn't announced prominently.

Even these examples don’t top how this phenomenon is the most applicable to life. 

We've all had bad days and sometimes we wonder whether or not having a bad day yields a succession of these days. When you're having a particularly bad day out of the norm, rest assured mathematically due to regression to the mean, your next day is likely to be better than before! :)

Have a nice day!



[1] Galton, F. (1886). Regression Towards Mediocrity in Hereditary Stature. The Journal of the Anthropological Institute of Great Britain and Ireland, 15, 246-263. doi:10.2307/2841583

[2] Morton, V., & Torgerson, D. J. (2003). Effect of regression to the mean on decision making in health care. BMJ (Clinical research ed.), 326(7398), 1083-4.


Images and image data belongs to KrIsMa.