I need to simulate scenarios like the following: "You have a deck of
3 orange cards, 5 yellow cards, and 2 blue cards. You draw a card,
replace it, and repeat N times."
So, I wrote the following code, which works, but it seems quite slow
to me. Can anyone point out some obvious thing that I'm doing
inefficiently? Or, is this more or less as good as it gets?
For reference, my typical numbers look like this:
2 <= len(population) <= 7
4 <= len(mapping) <= 50
10 <= count <= 1000000
B.
<code>
#!/usr/bin/env python
import random
def randomDrawing(c ount, population):
"""Simulate s drawing <countitems from <population>, with
replacement.
population is a list of lists: [[count1, type1], [count2,
type2], ...]
Typical examples:
>>>randomDrawin g(100, [[3, 'orange'], [5, 'yellow'], [2, 'blue']])
[[28, 'orange'], [57, 'yellow'], [15, 'blue']]
>>>randomDrawin g(100000, [[3, 'orange'], [5, 'yellow'], [2,
'blue']])
[[29923, 'orange'], [50208, 'yellow'], [19869, 'blue']]
"""
res = [[0, item[1]] for item in population]
mapping = []
for i in xrange(len(popu lation)):
mapping.extend([i]*population[i][0])
for i in xrange(count):
index = random.choice(m apping)
res[index][0] += 1
return res
</code>
--
Brendon Towle, PhD
Cognitive Scientist
+1-412-690-2442x127
Carnegie Learning, Inc.
The Cognitive Tutor Company ®
Helping over 375,000 students in 1000 school districts succeed in math. 2 2199
Brendon Towle wrote:
I need to simulate scenarios like the following: "You have a deck of 3
orange cards, 5 yellow cards, and 2 blue cards. You draw a card, replace
it, and repeat N times."
So, I wrote the following code, which works, but it seems quite slow to
me. Can anyone point out some obvious thing that I'm doing
inefficiently? Or, is this more or less as good as it gets?
For reference, my typical numbers look like this:
2 <= len(population) <= 7
4 <= len(mapping) <= 50
10 <= count <= 1000000
B.
<code>
#!/usr/bin/env python
import random
def randomDrawing(c ount, population):
"""Simulate s drawing <countitems from <population>, with replacement.
population is a list of lists: [[count1, type1], [count2, type2], ...]
Typical examples:
>>>randomDrawin g(100, [[3, 'orange'], [5, 'yellow'], [2, 'blue']])
[[28, 'orange'], [57, 'yellow'], [15, 'blue']]
>>>randomDrawin g(100000, [[3, 'orange'], [5, 'yellow'], [2, 'blue']])
[[29923, 'orange'], [50208, 'yellow'], [19869, 'blue']]
"""
res = [[0, item[1]] for item in population]
mapping = []
for i in xrange(len(popu lation)):
mapping.extend([i]*population[i][0])
for i in xrange(count):
index = random.choice(m apping)
res[index][0] += 1
return res
</code>
--Brendon Towle, PhD
Cognitive Scientist
+1-412-690-2442x127
Carnegie Learning, Inc.
The Cognitive Tutor Company ®
Helping over 375,000 students in 1000 school districts succeed in math.
Given the data structure, might it not be faster to generate binomial
variates for n-1 types, and set nth count = #draws - sum(other
outcomes)? And for a "large" count, could you get by with a normal
approximation? If you *do* feel the need for exact binomial, there are
short, somewhat sluggish routines in Devroye (1986 - on the web!, pg
525), and Random_binomial 1, compiled by Alan Miller(AMrandom .zip0,
available, xlated, at http://www.esbconsult.com/. Even though they are
relatively slow, generating a few of these would seem to be a lot faster
than your current approach.
Sorry I can't help more - I'm just starting to learn Python, have yet to
even get IDLE going.
Regards,
Dave Braden
Brendon Towle wrote:
I need to simulate scenarios like the following: "You have a deck of
3 orange cards, 5 yellow cards, and 2 blue cards. You draw a card,
replace it, and repeat N times."
So, I wrote the following code, which works, but it seems quite slow
to me. Can anyone point out some obvious thing that I'm doing
inefficiently? Or, is this more or less as good as it gets?
For reference, my typical numbers look like this:
2 <= len(population) <= 7
4 <= len(mapping) <= 50
10 <= count <= 1000000
B.
<code>
#!/usr/bin/env python
import random
def randomDrawing(c ount, population):
"""Simulate s drawing <countitems from <population>, with
replacement.
population is a list of lists: [[count1, type1], [count2,
type2], ...]
Typical examples:
>>>randomDrawin g(100, [[3, 'orange'], [5, 'yellow'], [2, 'blue']])
[[28, 'orange'], [57, 'yellow'], [15, 'blue']]
>>>randomDrawin g(100000, [[3, 'orange'], [5, 'yellow'], [2,
'blue']])
[[29923, 'orange'], [50208, 'yellow'], [19869, 'blue']]
"""
res = [[0, item[1]] for item in population]
mapping = []
for i in xrange(len(popu lation)):
mapping.extend([i]*population[i][0])
for i in xrange(count):
index = random.choice(m apping)
res[index][0] += 1
return res
</code>
--
Brendon Towle, PhD
Cognitive Scientist
+1-412-690-2442x127
Carnegie Learning, Inc.
The Cognitive Tutor Company ®
Helping over 375,000 students in 1000 school districts succeed in math.
I got nearly a 2x speed up with this variant:
def randomDrawing3( count, population):
res = [[0, item[1]] for item in population]
mapping = []
for i in xrange(len(popu lation)):
mapping.extend([i]*population[i][0])
n = len(mapping)
for i in xrange(count):
index = int(n * random.random() )
res[mapping[index]][0] += 1
return res
Apparently "int(n * random.random() )" is faster than random.choice()
or random.randint( )
sforman@garbage :~ $ python -mtimeit -s'import random; n=10' 'int(n *
random.random() )'
100000 loops, best of 3: 3.22 usec per loop
sforman@garbage :~ $ python -mtimeit -s'import random; n=10'
'random.randint (1, n)'
100000 loops, best of 3: 13 usec per loop
sforman@garbage :~ $ python -mtimeit -s'import random; n=range(10)'
'random.choice( n)'
100000 loops, best of 3: 6.07 usec per loop
(Note that the first and last examples produce values 0..9 while the
middle one produces 1..10)
I don't know for sure, but I think the random, uh, spread or whatever
will be the same for random() as for choice(). If it's important, you
should verify that. ;-)
Peace,
~Simon This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Constandinos Mavromoustakis |
last post by:
Dear all,
first we apologize if you receive multiple copies of this announcement.
please see below if you are interested.
Thank you in advance.
============================================================================
=
|
by: Paul Rubin |
last post by:
http://www.nightsong.com/phr/python/sharandom.c
This is intended to be less predicable/have fewer correlations than
the default Mersenne Twister or Wichmann-Hill generators. Comments
are appreciated.
|
by: Constandinos Mavromoustakis |
last post by:
http://agent.csd.auth.gr/~cmavrom
--------------------------------------------------
============================================================================
=
37th Annual Simulation Symposium
April 18 - 22, 2004
Hyatt Regency Crystal City
|
by: Gus |
last post by:
----------------------------------------------------------------------------
------------------------------------
Call for Papers: 38th Annual Simulation Symposium
Part of the 2005 Spring Simulation Multiconference
San Diego, April 2-8, 2005
Hilton Mission Valley Hotel
|
by: Karatza Helen |
last post by:
Our apologies if you have received multiple copies
--------------------------------------------------
Call for Papers: 38th Annual Simulation Symposium
Part of the 2005 Spring Simulation Multiconference
San Diego, April 2-8, 2005
Hilton Mission Valley Hotel
| |
by: Marc Dansereau |
last post by:
Hi all
I am new to this forum and to the c programming language.
If I understand, the random() function in C return numbers that follow a
uniform distribution U(0,1). Can somebody know how to generate a set of
random number that follow a normal distribution N(0,1) ? I am develloping
on power4 machine running AIX.
Thank you for your help
|
by: tshad |
last post by:
I am trying to set up an Image authorization where you type in the value
that is in a picture to log on to our site.
I found a program that is supposed to do it, but it doesn't seem to work.
It should put a blue and yellow box on the page with "This is a test" as
part of the picture. But what I get is a broken Gif.
The other problem is that I can't view the source???? The view source is
disabled for this page. What causes this?
|
by: Intiha |
last post by:
Hello all,
I am trying to generate random seeds for my simulations.
currently i was using srand(time(NULL); for this purpose.
But for confidence in my results i ran it using a script in a loop.
Since the time b/w execution is very similar, many simulation runs
resulted in exact same results.
Is there a better way of seeding the random number generator in c/c++
|
by: Mike Langworthy |
last post by:
i can not seem to get this code to work. someone please help
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |