aboutsummaryrefslogtreecommitdiff
path: root/src/random.c
blob: 0112ebd55e8ebfc2651e8ac01f3f3cd8db5c5393 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* Copyright (c) 2019, Anthony Latorre <tlatorre at uchicago>
 *
 * 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, see <https://www.gnu.org/licenses/>.
 */

#include "random.h"
#include <math.h>

double randn(void)
{
    /* Generates a random number from a normal distribution using the
     * Box-Muller transform. */
    double u1, u2;

    u1 = genrand_real1();
    u2 = genrand_real1();

    return sqrt(-2*log(u1))*cos(2*M_PI*u2);
}

void rand_sphere(double *dir)
{
    /* Generates a random point on the unit sphere. */
    double u, v, theta, phi;

    u = genrand_real1();
    v = genrand_real1();

    phi = 2*M_PI*u;
    theta = acos(2*v-1);

    dir[0] = sin(theta)*cos(phi);
    dir[1] = sin(theta)*sin(phi);
    dir[2] = cos(theta);
}