pi_capi.c (2989B)
1 /* 2 Copyright 2010-2011, D. E. Shaw Research. 3 All rights reserved. 4 5 Redistribution and use in source and binary forms, with or without 6 modification, are permitted provided that the following conditions are 7 met: 8 9 * Redistributions of source code must retain the above copyright 10 notice, this list of conditions, and the following disclaimer. 11 12 * Redistributions in binary form must reproduce the above copyright 13 notice, this list of conditions, and the following disclaimer in the 14 documentation and/or other materials provided with the distribution. 15 16 * Neither the name of D. E. Shaw Research nor the names of its 17 contributors may be used to endorse or promote products derived from 18 this software without specific prior written permission. 19 20 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 */ 32 #include <Random123/threefry.h> 33 #include <stdio.h> 34 #include <assert.h> 35 36 /* Everyone's favorite PRNG example: calculate pi/4 by throwing darts 37 // at a square board and counting the fraction that are inside the 38 // inscribed circle. 39 40 // This version uses the C API to threefry2x64. */ 41 42 #include "pi_check.h" 43 44 int main(int argc, char **argv){ 45 unsigned long hits = 0, tries = 0; 46 const int64_t two_to_the_62 = ((int64_t)1)<<62; 47 48 threefry2x64_key_t key = {{0, 0}}; 49 threefry2x64_ctr_t ctr = {{0, 0}}; 50 enum { int32s_per_counter = sizeof(ctr)/sizeof(int32_t) }; 51 (void)argc;(void)argv; /* unused */ 52 53 printf("Throwing %lu darts at a square board using threefry2x64\n", NTRIES); 54 55 /* make the most of each bijection by looping over as many 56 int32_t's as we can find in the ctr_type. */ 57 assert( int32s_per_counter%2 == 0 ); 58 while(tries < NTRIES){ 59 /* Use a union to avoid strict aliasing issues. */ 60 union{ 61 threefry2x64_ctr_t ct; 62 int32_t i32[int32s_per_counter]; 63 }u; 64 size_t j; 65 /* Don't worry about the 'carry'. We're not going to loop 66 more than 2^64 times. */ 67 ctr.v[0]++; 68 u.ct = threefry2x64(ctr, key); 69 for(j=0; j<int32s_per_counter; j+=2){ 70 int64_t x = u.i32[j]; 71 int64_t y = u.i32[j+1]; 72 if( (x*x + y*y) < two_to_the_62 ) 73 hits++; 74 tries++; 75 } 76 } 77 return pi_check(hits, tries); 78 }