Created
November 21, 2021 22:27
-
-
Save timbuckley/869f6bf7699a8330baedc7429abd5b32 to your computer and use it in GitHub Desktop.
Does polling work? (Yes)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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