Skip to content

Main content

Confidence Interval for a Proportion Source Code

Browse the implementation files for Confidence Interval for a Proportion.
tool.ts typescript
import { parseFiniteNumber } from '../../parse/number/tool';

const Z_SCORES: Record<string, number> = {
	'90': 1.6448536269514722,
	'95': 1.959963984540054,
	'99': 2.5758293035489004
};

export const confidenceIntervalForProportion = (
	successesInput: unknown,
	sampleSizeInput: unknown,
	confidenceInput: unknown
): string => {
	const successes = parseFiniteNumber(successesInput);
	const sampleSize = parseFiniteNumber(sampleSizeInput);
	const confidence = String(confidenceInput ?? '');
	const zScore = Z_SCORES[confidence];
	if (
		successes === null ||
		sampleSize === null ||
		!Number.isSafeInteger(successes) ||
		!Number.isSafeInteger(sampleSize) ||
		sampleSize < 1 ||
		successes < 0 ||
		successes > sampleSize ||
		zScore === undefined
	) {
		return '';
	}

	const proportion = successes / sampleSize;
	const margin =
		zScore *
		Math.sqrt((proportion * (1 - proportion)) / sampleSize);
	return `${Math.max(0, proportion - margin).toFixed(
		4
	)},${Math.min(1, proportion + margin).toFixed(4)}`;
};

export const Tool: TypeTool = {
	name: 'Confidence Interval for a Proportion',
	slug: 'statistics/confidence-interval-proportion',
	intro:
		'Estimate a population proportion with a two-sided normal-approximation interval.',
	tool: confidenceIntervalForProportion,
	i: [
		{
			example: '60',
			label: 'Successes',
			placeholder: 'Number of successes',
			type: 'number'
		},
		{
			example: '100',
			label: 'Sample Size',
			placeholder: 'Total sample size',
			type: 'number'
		},
		{
			label: 'Confidence Level',
			options: [
				{ text: '90%', value: '90' },
				{ selected: true, text: '95%', value: '95' },
				{ text: '99%', value: '99' }
			],
			placeholder: 'Confidence level',
			type: 'select',
			value: '95'
		}
	],
	o: [
		{
			example: '0.5040,0.6960',
			label: 'Confidence Interval',
			placeholder: 'Lower and upper bounds will appear here...',
			render: 'textarea',
			type: 'text'
		}
	],
	equation:
		'$$\\hat{p}\\pm z\\sqrt{\\frac{\\hat{p}(1-\\hat{p})}{n}}$$'
};

export default Tool;

Description

Browse the implementation files for Confidence Interval for a Proportion.

References

  1. Tool.io on GitHub
  2. Tool.io TypeScript tools library

Similar or alternative tools