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


Groups > comp.lang.python > #92287 > unrolled thread

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

Started by"C.D. Reimer" <chris@cdreimer.com>
First post2015-06-07 11:40 -0700
Last post2015-06-07 11:40 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

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

From"C.D. Reimer" <chris@cdreimer.com>
Date2015-06-07 11:40 -0700
SubjectRe: Python Random vs. Cython C Rand for Dice Rolls
Message-ID<mailman.270.1433702448.13271.python-list@python.org>
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.

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web