math.c

/**
 * Copyright (c) 2024, SWGY, Inc. <ron@sw.gy>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <math.h> /* cos, sqrt, M_PI */
#include <stdlib.h> /* arc4random, rand */

double
normal(double mean, double stddev)
{
	/* Box-Muller method, transcribed from Wikipedia */
	double u, v;
	double x;
#ifdef __OpenBSD__
	u = arc4random_uniform(100000) / 100000.0;
	v = arc4random_uniform(100000) / 100000.0;
#else
	/* srand should have been called prior to this point */
	u = (float)rand() / (float)RAND_MAX;
	v = (float)rand() / (float)RAND_MAX;
#endif
	x = sqrt(-2 * log(u)) * cos(2 * M_PI * v);
	return mean + x * stddev;
}