Skip to content

Instantly share code, notes, and snippets.

@kausality
Last active October 9, 2015 22:33
Show Gist options
  • Save kausality/59484e9cbe2ef253135c to your computer and use it in GitHub Desktop.
Save kausality/59484e9cbe2ef253135c to your computer and use it in GitHub Desktop.
Simulating Sampling distribution of Sample mean is a Normal distribution
# Created on GNU Octave 3.8.1
# Demonstrates that Sampling Distribution of the Sample Mean follows a Normal Distribution
global max=30; # Numbers 1-max for which to generate probability table
global dist; # Stores the probability distribution table: dist(1,x)->probability, dist(2,x)->Number
# Generate probability distribution table for total of max numbers
function randgen
global max;
global dist;
dist=zeros(2,max);
for i=1:max
dist(1,i)=rand;
endfor
cumulative=0;
for i=1:max
cumulative=cumulative+dist(1,i);
endfor
for i=1:max
dist(1,i)=dist(1,i)/cumulative;
endfor
cumulative=0;
dist(1,:)=sort(dist(1,:));
for i=1:max
dist(2,i)=i;
endfor
endfunction
# Pick a nummber based on probability distribution generated by randgen
function val=randchoose()
global max;
global dist;
num=rand;
for i=1:max
val=dist(2,i);
if num<=dist(1,i)
return;
else
num=num-dist(1,i);
endif
endfor
endfunction
# Plot frequency distribution of means of sample of size sampleSize taken over n_experiment times
function plotdist(sampleSize)
global max
global dist;
n_experiment=1500;
frequency=[];
meanofmeans=0;
for i=1:n_experiment
sampleSum=0;
for j=1:sampleSize
sampleSum+=randchoose();
endfor
sampleMean=sampleSum/sampleSize;
meanofmeans+=sampleMean;
frequency=[frequency sampleMean];
endfor
meanofmeans=meanofmeans/n_experiment;
hist(frequency,30);
# This approaches the population mean
printf("\n\nMean of all Sample means: %f\n\n",meanofmeans);
endfunction
# Calculate population mean
function popmean=populationMean()
global max;
global dist;
popmean=0;
for i=1:max
popmean+=dist(1,i)*dist(2,i);
endfor
endfunction
# Used to compare Sample means of various sample sizes with the Population mean
function calcSampleMeans(sampleSize)
global max;
global dist;
sampleSum=0;
for i=1:sampleSize
sampleSum+=randchoose();
endfor
sampleMean=sampleSum/sampleSize;
printf("Sample Mean %f\n",sampleMean);
endfunction
function main()
randgen();
sampleSize=50;
plotdist(30);
sizes=[5 15 30 50 60 100];
printf("Population mean:%f\n\n",populationMean());
for i=1:length(sizes)
printf("\nFor Sample size:%d\n",sizes(i));
calcSampleMeans(sizes(i));
endfor
endfunction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment