nrand48.c 1.87 KB
Newer Older
1
/*****************************************************************************
2
 * nrand48.c: POSIX erand48(), jrand48() and nrand48() replacements
3 4 5
 *****************************************************************************
 * Copyright © 2010 Rémi Denis-Courmont
 *
6 7 8
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
9 10 11 12
 * (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
Jean-Baptiste Kempf's avatar
Jean-Baptiste Kempf committed
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU Lesser General Public License for more details.
15 16
 *
 * You should have received a copy of the GNU Lesser General Public License
17 18
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
19 20 21 22 23 24 25 26
 *****************************************************************************/

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <inttypes.h>

27
static uint64_t iterate48 (unsigned short subi[3])
28
{
29
    const uint64_t a = UINT64_C(0x5DEECE66D);
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
    const unsigned c = 13;
    const uint64_t mask = UINT64_C(0xFFFFFFFFFFFF); // 48 bits

    uint64_t x = ((uint64_t)subi[0] << 32)
               | ((uint32_t)subi[1] << 16)
               | subi[2];

    x *= a;
    x += c;
    x &= mask;

    subi[0] = (x >> 32) & 0xFFFF;
    subi[1] = (x >> 16) & 0xFFFF;
    subi[2] = (x >>  0) & 0XFFFF;

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
    return x;
}

double erand48 (unsigned short subi[3])
{
    uint64_t r = iterate48 (subi);
    return ((double)r) / 281474976710655.;
}

long jrand48 (unsigned short subi[3])
{
    return ((int64_t)iterate48 (subi)) >> 16;
}

long nrand48 (unsigned short subi[3])
{
    return iterate48 (subi) >> 17;
62
}