Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #92287

Re: Python Random vs. Cython C Rand for Dice Rolls

Date 2015-06-07 11:40 -0700
From "C.D. Reimer" <chris@cdreimer.com>
Subject Re: Python Random vs. Cython C Rand for Dice Rolls
References <55747C96.7090006@cdreimer.com> <CAPTjJmo0Aw961q54BySZBSDdD8xqCPFjMezcytzWxrE0m6afTw@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.270.1433702448.13271.python-list@python.org> (permalink)

Show all headers | View raw


On 6/7/2015 10:33 AM, Chris Angelico wrote:
> The negative result is a strong indicator that you're not seeing the
> results of rand() here. While there is a potential for bias (check out
> RAND_MAX, and consider that there may be some small bias there;
> although on most modern systems, RAND_MAX is going to be high enough
> that the bias from modulo 6 won't be highly visible), it's much MUCH
> more likely that you're looking at uninitialized memory.

Here's the revised Cython code.

cdef extern from "stdlib.h":

     int c_libc_rand "rand"()

cdef int f[12]

     

def roll(int x):

     cdef:

         int a = 0, b = 0, i = 0

     for i in range(x):

         a = c_libc_rand() % 6 + 1

         b = c_libc_rand() % 6 + 1
         

         f[(a + b) - 1] += 1

     return f


Here's the new console output.

PS Z:\projects\programming\python\basic_games\fastdice> python test_fastdice.py

TOTAL SPOTS     NUMBER OF TIMES

  2                1389911

  3                2777722

  4                4168248

  5                5553632

  6                6944907

  7                8334670

  8                6945597

  9                5553557

  10               4167485

  11               2775806

  12               1388465

1.65599989891


I had to put the array definition outside of the function declaration, 
where it's automatically initialized to zero in the global space. I 
tried to initialize the array from inside the function but Cython threw 
up errors, either the C declaration wasn't correct or unable to convert 
from C to Python when updating the array elements. I'll figure out that 
problem later. The new version works as expected.

Thanks,

Chris R.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Python Random vs. Cython C Rand for Dice Rolls "C.D. Reimer" <chris@cdreimer.com> - 2015-06-07 11:40 -0700

csiph-web