Skip to content

Instantly share code, notes, and snippets.

@timbuckley
Created November 21, 2021 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timbuckley/869f6bf7699a8330baedc7429abd5b32 to your computer and use it in GitHub Desktop.
Save timbuckley/869f6bf7699a8330baedc7429abd5b32 to your computer and use it in GitHub Desktop.
Does polling work? (Yes)
const US_ADULT_POPULATION = 245e6;
const populationSize = US_ADULT_POPULATION;
const defaultSampleSize = 15000;
type Individual = number;
type Population = Individual[];
type Sample = Individual[];
main();
function main(): void {
const population = createPopulation(populationSize);
const sample = takeSample(population, defaultSampleSize);
const sampleMean = average(sample);
const populationMean = average(population);
console.log(`Sample mean: ${sampleMean}`);
console.log(`Population mean: ${populationMean}`);
}
/**
* Creates a population size with a random distribution.
*/
function createPopulation(populationSize: number): Population {
return Array.from({ length: populationSize }, () => Math.random());
}
/**
* Takes a sample of the provided population.
*/
function takeSample(population: Population, sampleSize: number = defaultSampleSize): Sample {
return population.sort(() => Math.random() - 0.5).slice(0, sampleSize);
}
/**
* Calculates the mean of a sample.
*/
function average(sample: number[]) {
return sample.reduce((acc, curr) => acc + curr) / sample.length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment