Skip to content

Main content

Beta Distribution Sampler Source Code

Browse the implementation files for Beta Distribution Sampler.
tool.ts typescript
// Tool: Beta Distribution Sampler

const parsePositive = (input: unknown): number | null => {
	const value =
		typeof input === 'string' || typeof input === 'number'
			? Number(input)
			: NaN;
	return Number.isFinite(value) && value > 0 ? value : null;
};

const createRandom = (seed: string): (() => number) => {
	let state = 2166136261;
	for (const character of seed) {
		state ^= character.charCodeAt(0);
		state = Math.imul(state, 16777619);
	}
	return () => {
		state += 0x6d2b79f5;
		let value = state;
		value = Math.imul(value ^ (value >>> 15), value | 1);
		value ^=
			value + Math.imul(value ^ (value >>> 7), value | 61);
		return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
	};
};

const gammaSample = (
	shape: number,
	random: () => number
): number => {
	if (shape < 1) {
		return (
			gammaSample(shape + 1, random) * random() ** (1 / shape)
		);
	}
	const d = shape - 1 / 3;
	const c = 1 / Math.sqrt(9 * d);
	while (true) {
		const first = Math.max(Number.MIN_VALUE, random());
		const second = random();
		const normal =
			Math.sqrt(-2 * Math.log(first)) *
			Math.cos(2 * Math.PI * second);
		const base = 1 + c * normal;
		if (base <= 0) continue;
		const value = base ** 3;
		const uniform = random();
		if (
			uniform < 1 - 0.0331 * normal ** 4 ||
			Math.log(uniform) <
				0.5 * normal ** 2 + d * (1 - value + Math.log(value))
		) {
			return d * value;
		}
	}
};

const round = (value: number): number =>
	Number(value.toPrecision(12));

export const sampleBetaDistribution = (
	alphaInput: unknown,
	betaInput: unknown,
	sampleCountInput: unknown,
	seedInput: unknown
): string => {
	const alpha = parsePositive(alphaInput);
	const beta = parsePositive(betaInput);
	const sampleCount = Number(sampleCountInput);
	if (
		alpha === null ||
		beta === null ||
		!Number.isSafeInteger(sampleCount) ||
		sampleCount < 1 ||
		sampleCount > 5_000 ||
		typeof seedInput !== 'string' ||
		seedInput.trim() === ''
	)
		return '';

	const random = createRandom(seedInput);
	const samples: number[] = [];
	for (let index = 0; index < sampleCount; index += 1) {
		const first = gammaSample(alpha, random);
		const second = gammaSample(beta, random);
		const sample = first / (first + second);
		if (!Number.isFinite(sample)) return '';
		samples.push(round(sample));
	}
	const sampleMean =
		samples.reduce((sum, value) => sum + value, 0) /
		sampleCount;

	return JSON.stringify(
		{
			alpha,
			beta,
			sampleCount,
			sampleMean: round(sampleMean),
			samples,
			seed: seedInput,
			theoreticalMean: round(alpha / (alpha + beta)),
			theoreticalVariance: round(
				(alpha * beta) /
					((alpha + beta) ** 2 * (alpha + beta + 1))
			)
		},
		null,
		2
	);
};

export const Tool: TypeTool = {
	name: 'Beta Distribution Sampler',
	slug: 'probability/beta-distribution-sampler',
	intro:
		'Generate reproducible beta-distributed values from two independently sampled gamma variates.',
	tool: sampleBetaDistribution,
	i: [
		{
			example: '2',
			label: 'Alpha',
			placeholder: 'Positive first shape parameter',
			type: 'number',
			value: 2
		},
		{
			example: '5',
			label: 'Beta',
			placeholder: 'Positive second shape parameter',
			type: 'number',
			value: 5
		},
		{
			example: '100',
			label: 'Samples',
			placeholder: 'Sample count from 1 to 5000',
			type: 'number',
			value: 100
		},
		{
			example: 'tool.io',
			label: 'Seed',
			placeholder: 'Seed for reproducible values',
			type: 'text',
			value: 'tool.io'
		}
	],
	o: [
		{
			example: '{ "samples": [], "sampleMean": 0.2857 }',
			label: 'Beta Samples',
			placeholder: 'Sampled values will appear here...',
			render: 'textarea',
			type: 'text'
		}
	],
	cite: [
		{
			title: 'A Simple Method for Generating Gamma Variables',
			url: 'https://doi.org/10.1145/358407.358414'
		},
		{
			title: 'Beta distribution — Wikipedia',
			url: 'https://en.wikipedia.org/wiki/Beta_distribution'
		}
	]
};

export default Tool;

Description

Browse the implementation files for Beta Distribution Sampler.

References

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

Similar or alternative tools