473,327 Members | 1,967 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

Random number generation

Hi there.
I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?

Dec 5 '06 #1
22 3386
ga***************@gmail.com said:
Hi there.
I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?
Yes, if you can get satisfactorily random bits from somewhere. (If you're
not overly fussy, rand() will supply them.)

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Dec 5 '06 #2
In article <11**********************@16g2000cwy.googlegroups. com>,
<ga***************@gmail.comwrote:
>I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?
Not in standard C, no. In order to generate random numbers, you
have to have a source of non-deterministic information -- something
that is random. C itself does not provide any true random operations,
and hacks such as getting the time of day or timing a loop tend not to
really be very random at all.

C provides some pseudo-random functions, the actual randomness of
which varies considerably with the implementation. The comp.lang.c FAQ
probably describes several possibilities, such as the
Mersenne Twister ( http://en.wikipedia.org/wiki/Mersenne_twister )
implementations of which are fairly easily available.

--
Is there any thing whereof it may be said, See, this is new? It hath
been already of old time, which was before us. -- Ecclesiastes
Dec 5 '06 #3
<ga***************@gmail.comwrote in message
news:11**********************@16g2000cwy.googlegro ups.com...
Hi there.
I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?
It depends on what you mean by "random".

If you mean "random" in the sense that the algorithm passes certain
statistical tests of randomness, then there may be one or two built into the
C library, but also you can roll your own (see the URLs at the end). There
are at least a few algorithms based on prime moduli, eliptic curves, etc.
The output of these algorithms would be suitable for simulations and similar
activities where an "opponent" is not involved. Every random number
algorithm that I'm aware of has (a)a "seed" or "internal state", and (b)a
finite period in which the generated sequence will repeat. The typical
period is at least 2^31 or so, but I'm sure there are those with much larger
periods. (Algorithms like this are really pseudo-random, not random.)

If you mean "random" in the sense that an attacker cannot guess what the
next number will be ... then you have to be far more careful. (In fact,
RSA's Securid product line is designed to make this very hard.) If you're
dealing with cryptography ... the notion of statistical randomness is
unrelated to the notion of whether an attacker can elicit the algorithm
and/or the seed ... an algorithm can pass statistical tests but not be
suitable if its goal is to prevent guessing the next number. (In fact, you
might want to review the notion of the one-time cryptopad ... these are best
based on physical processes, such as tossing a coin.)

Helpful URLs:

http://en.wikipedia.org/wiki/Pseudor...mber_generator

http://en.wikipedia.org/wiki/List_of...ber_generators

http://www.rsasecurity.com/node.asp?id=3050

http://www.random.org/

http://random.mat.sbg.ac.at/generators/

http://random.mat.sbg.ac.at/links/rando.html

http://www.agner.org/random/


Dec 5 '06 #4
<ga***************@gmail.comwrote:
I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?
RAND_MAX is a known constant on a C system. If the number drawn via rand()
is less than 0.8 * RAND_MAX, return a 1 from a function you write, else
return a 0. Ignore blather about real vs. pseudo and bad generator war
stories. A person who was interested in such stuff wouldn't have asked the
question you asked.
Dec 5 '06 #5
ga***************@gmail.com wrote:
Hi there.
I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?
Of course it is possible. There are numerous solutions, but here is one
that I believe will be intuitively satisfactory.
Suppose the largest number you want ever to see is 2*N+1 where N <=
RAND_MAX. Generate two random numbers, the first one ('First') scaled
to the range (0,N). If the second is less than .8 * RAND_MAX, return
2*FIRST, otherwise return 2*FIRST + 1.
Dec 5 '06 #6
"osmium" <r1********@comcast.netwrites:
<ga***************@gmail.comwrote:
>I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?

RAND_MAX is a known constant on a C system. If the number drawn via rand()
is less than 0.8 * RAND_MAX, return a 1 from a function you write, else
return a 0. Ignore blather about real vs. pseudo and bad generator war
stories. A person who was interested in such stuff wouldn't have asked the
question you asked.
I don't think we know that. Someone could have any number of reasons
for wanting the kind of random numbers the OP asked about. He may or
may not be concerned about predictability or the various measure of
randomness.

Truly random numbers are impossible without some kind of hardware
assistance. There are a number of ways to generate pseudo-random
numbers. The standard rand() function is one of them, but in practice
it's often not very good, and it definitely shouldn't be used in an
application where predictability would create a security problem.
There are other, likely better, algorithms that can be implemented in
standard C, and yet other techniques that depend on system-specific
features (<OT>/dev/random, /dev/urandom</OT>). As the saying goes,
"The generation of random numbers is too important to be left to
chance." (attributed to Robert R. Coveyou). Or, as John von Neumann
put it, "Anyone who considers arithmetical methods of producing random
digits is, of course, in a state of sin."

The OP may or may not care about any of this, but it's all good to
know even if it's not immediately relevant.

Also, the original question is ambiguous. If he wanted to get 0 80%
of the time and 1 20% of the time, that would be unambiguous (and
consistent with the requirement as stated), but he said he wants even
and odd numbers respectively 80% and 20% of the time. But he *might*
want numbers over some range, with a bias in favor of even numbers.

To the original poster: Do you care *which* even or odd numbers you
get? Please post a followup and clarify the question for us.

Also, the technique of using the result of rand() and returning 0 the
range 0 to 0.8*RAND_MAX could introduce a bias if the total number of
possible results from RAND_MAX is not a multiple of 5, even if the
results returned by rand() are properly distributed. The bias is
going to be small, since RAND_MAX is at least 32767, so this may or
may not matter. If it does, you can avoid the problem by reducing the
range of numbers; this can be done by rejecting a few values at the
top end of the range, calling rand() repeatedly until you get a number
that's in the range you need. Figuring out what the range should be,
and writing the code to implement this, are left as exercises.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 5 '06 #7
On 5 Dec 2006 10:15:13 -0800, in comp.lang.c ,
ga***************@gmail.com wrote:
>Hi there.
I want to generate random numbers with a given probability, say 80%
even and 20% odd.
by definition, such numbers arent random.... :-)
Is it possible to implement such an algorithm in C?
Yes, but its not really a C problem, itsan algorithm problem, and
probably better suited for comp.programming or a maths group.

--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Dec 5 '06 #8
ga***************@gmail.com wrote:
Hi there.
I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?
Ignoring the problem of the quality of the PRNG in C, this is fairly
straightforward:

#include <stdlib.h>

int rand80_20() {
int r;
do {
if (0 == ((r = rand ()) & 1) || 0 == (rand()&3)) break;
} while(1);
return r;
}

How and why this works is left as an exercise to the reader. :)

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Dec 5 '06 #9
osmium wrote:
<ga***************@gmail.comwrote:
I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?

RAND_MAX is a known constant on a C system. If the number drawn via rand()
is less than 0.8 * RAND_MAX, return a 1 from a function you write, else
return a 0.
I don't think the OP was loking for 0 and 1 as the only value outputs.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Dec 5 '06 #10
<we******@gmail.comwrote:
osmium wrote:
><ga***************@gmail.comwrote:
I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?

RAND_MAX is a known constant on a C system. If the number drawn via
rand()
is less than 0.8 * RAND_MAX, return a 1 from a function you write, else
return a 0.

I don't think the OP was loking for 0 and 1 as the only value outputs.
I thought I recognized "earth speak" and on that planet, 100% is all there
is. YMMV.
Dec 5 '06 #11
In article <4p********************************@4ax.com>,
Mark McIntyre <ma**********@spamcop.netwrote:
>On 5 Dec 2006 10:15:13 -0800, in comp.lang.c ,
ga***************@gmail.com wrote:
>>I want to generate random numbers with a given probability, say 80%
even and 20% odd.
>by definition, such numbers arent random.... :-)
Sure they are (if they could be randomly generated at all).
They just don't have a uniform distribution.

Throw two fair-weighted six-sided dice. The total of the upwards
faces is random in the range 2 to 12 -- but the total will not
have a uniform random distribution. (e.g., 2 and 12 will each have
probability 1/36; 7 will have probability 1/6).
--
"No one has the right to destroy another person's belief by
demanding empirical evidence." -- Ann Landers
Dec 5 '06 #12
"osmium" <r1********@comcast.netwrites:
<we******@gmail.comwrote:
>osmium wrote:
>><ga***************@gmail.comwrote:
I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?

RAND_MAX is a known constant on a C system. If the number drawn via
rand()
is less than 0.8 * RAND_MAX, return a 1 from a function you write, else
return a 0.

I don't think the OP was loking for 0 and 1 as the only value outputs.

I thought I recognized "earth speak" and on that planet, 100% is all there
is. YMMV.
The OP asked for even and odd, not for 0 and 1. He didn't say enough
about *which* even or odd numbers he wants; until he does, I suggest
there's not much point in guessing what he actually meant.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 6 '06 #13
Martin Ambuhl wrote:
ga***************@gmail.com wrote:
>I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?

Of course it is possible. There are numerous solutions, but here is
one that I believe will be intuitively satisfactory.
Suppose the largest number you want ever to see is 2*N+1 where N <=
RAND_MAX. Generate two random numbers, the first one ('First')
scaled to the range (0,N). If the second is less than .8 * RAND_MAX,
return 2*FIRST, otherwise return 2*FIRST + 1.
Most (not all) random generators will never generate a zero
(because that value gets them into an infinite loop). If you know
this you can take advantage by conditionally subtracting one after
the odd/even decision.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>
Dec 6 '06 #14
In article <4p********************************@4ax.com>,
Mark McIntyre <ma**********@spamcop.netwrote:
>>I want to generate random numbers with a given probability, say 80%
even and 20% odd.
>by definition, such numbers arent random.... :-)
You have too narrow a definition of random. Random does not imply
any particular distribution of values.
>Is it possible to implement such an algorithm in C?

Yes, but its not really a C problem, itsan algorithm problem, and
probably better suited for comp.programming or a maths group.
On the other hand, it's pretty simple. First generate a random number
to choose whether to pick an odd or even number - for example,
generate a random integer and if it's equal to 0 mod 5 you're going to
generate an odd number, otherwise an even one. Then generate another
integer - to make it even, double it; to make it odd, double it and
add one.

Of course, you probably really want numbers in some range, so you'll
have to modify it a bit.

-- Richard

--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Dec 6 '06 #15
CBFalconer <cb********@yahoo.comwrites:
[...]
Most (not all) random generators will never generate a zero
(because that value gets them into an infinite loop). If you know
this you can take advantage by conditionally subtracting one after
the odd/even decision.
I'd expect that to be the case only for RNGs where the value returned
is the same size as the entire state.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 6 '06 #16
CBFalconer wrote:
Martin Ambuhl wrote:
ga***************@gmail.com wrote:
I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?
Of course it is possible. There are numerous solutions, but here is
one that I believe will be intuitively satisfactory.
Suppose the largest number you want ever to see is 2*N+1 where N <=
RAND_MAX. Generate two random numbers, the first one ('First')
scaled to the range (0,N). If the second is less than .8 * RAND_MAX,
return 2*FIRST, otherwise return 2*FIRST + 1.

Most (not all) random generators will never generate a zero
(because that value gets them into an infinite loop).
I am not aware of *any* random number generator in practical usage with
this supposed property. Can you cite an example of one?

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Dec 6 '06 #17
ga***************@gmail.com wrote:
>
Hi there.
I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?
/* BEGIN new.c */

#include <stdio.h>
#include <stdlib.h>

int even80odd20(void);

int main(void)
{
int x, even, odd, e8o2;

for (even = odd = x = 0; x != 100; ++x) {
e8o2 = even80odd20();
printf("%d\n", e8o2);
if ((e8o2 & 1) != 0) {
++odd;
} else {
++even;
}
}
printf("\n%d even, %d odd\n", even, odd);
return 0;
}

int even80odd20(void)
{
int r = rand();

return RAND_MAX / 5 * 4 r ? r & ~1 : r | 1;
}

/* END new.c */
--
pete
Dec 6 '06 #18
Walter Roberson wrote:
>
.... snip ...
>
Throw two fair-weighted six-sided dice. The total of the upwards
faces is random in the range 2 to 12 -- but the total will not
have a uniform random distribution. (e.g., 2 and 12 will each have
probability 1/36; 7 will have probability 1/6).
Not if you let me use MY dice :-)

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>

Dec 6 '06 #19
we******@gmail.com wrote:
CBFalconer wrote:
>Martin Ambuhl wrote:
>>ga***************@gmail.com wrote:

I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?

Of course it is possible. There are numerous solutions, but here is
one that I believe will be intuitively satisfactory.
Suppose the largest number you want ever to see is 2*N+1 where N <=
RAND_MAX. Generate two random numbers, the first one ('First')
scaled to the range (0,N). If the second is less than .8 * RAND_MAX,
return 2*FIRST, otherwise return 2*FIRST + 1.

Most (not all) random generators will never generate a zero
(because that value gets them into an infinite loop).

I am not aware of *any* random number generator in practical usage with
this supposed property. Can you cite an example of one?
The simplified linear congruential r = mr % rmax; (the addend is
0). Also those based on polynomials, eg a CRC16 generator.

I didn't say they were good prngs. :-)

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>
Dec 6 '06 #20
CBFalconer wrote:
we******@gmail.com wrote:
CBFalconer wrote:
Martin Ambuhl wrote:
ga***************@gmail.com wrote:

I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?

Of course it is possible. There are numerous solutions, but here is
one that I believe will be intuitively satisfactory.
Suppose the largest number you want ever to see is 2*N+1 where N <=
RAND_MAX. Generate two random numbers, the first one ('First')
scaled to the range (0,N). If the second is less than .8 * RAND_MAX,
return 2*FIRST, otherwise return 2*FIRST + 1.

Most (not all) random generators will never generate a zero
(because that value gets them into an infinite loop).
I am not aware of *any* random number generator in practical usage with
this supposed property. Can you cite an example of one?

The simplified linear congruential r = mr % rmax; (the addend is
0). Also those based on polynomials, eg a CRC16 generator.

I didn't say they were good prngs. :-)
I wouldn't say they were prngs at all. And I'm not aware of anyone
else calling them that either. As far as I know, all serious PRNGs
will output 0 (or any other value in range) exactly 1/(1+RANDMAX)
proportion of the time.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Dec 6 '06 #21
On Wed, 6 Dec 2006 00:09:27 +0000 (UTC), in comp.lang.c ,
ro******@ibd.nrc-cnrc.gc.ca (Walter Roberson) wrote:
>In article <4p********************************@4ax.com>,
Mark McIntyre <ma**********@spamcop.netwrote:
>>On 5 Dec 2006 10:15:13 -0800, in comp.lang.c ,
ga***************@gmail.com wrote:
>>>I want to generate random numbers with a given probability, say 80%
even and 20% odd.
>>by definition, such numbers arent random.... :-)

Sure they are (if they could be randomly generated at all).
They just don't have a uniform distribution.
For some reason I read the OP's requirement as wanting 80% to be even,
and 20% to be odd.
>Throw two fair-weighted six-sided dice. The total of the upwards
faces is random in the range 2 to 12 -- but the total will not
have a uniform random distribution. (e.g., 2 and 12 will each have
probability 1/36; 7 will have probability 1/6).
You have two sets of random numbers here. :-)

FWIW I know what you're saying. BTW its probably how I'd solve the
OP's problem - generate two sets of random data, and an algo for
weighting them.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Dec 6 '06 #22
CBFalconer <cb********@yahoo.comwrote:
Martin Ambuhl wrote:
ga***************@gmail.com wrote:
I want to generate random numbers with a given probability, say 80%
even and 20% odd. Is it possible to implement such an algorithm in C?
Of course it is possible. There are numerous solutions, but here is
one that I believe will be intuitively satisfactory.
Suppose the largest number you want ever to see is 2*N+1 where N <=
RAND_MAX. Generate two random numbers, the first one ('First')
scaled to the range (0,N). If the second is less than .8 * RAND_MAX,
return 2*FIRST, otherwise return 2*FIRST + 1.

Most (not all) random generators will never generate a zero
(because that value gets them into an infinite loop). If you know
this you can take advantage by conditionally subtracting one after
the odd/even decision.
The Standard rand() can generate values from 0 to RAND_MAX, though.
While I don't think that means that it _must_ sometimes return 0, I'd
consider a version of rand() (or a replacement for it) that didn't to be
poor design. Amongst other reasons, you now have a function which
returns RAND_MAX (usually 2**N-1) values, rather than the expected
RAND_MAX+1 (usually 2**N), i.e. 0 through RAND_MAX.

Richard
Dec 8 '06 #23

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Nicholas Geraldi | last post by:
Im looking for a decent random number generator. Im looking to make a large number of random numbers (100 or so, if not more) in a short period of time (as fast as possible). the function i was...
10
by: Virus | last post by:
Ok well what I am trying to do is have 1.) the background color to change randomly with 5 different colors.(change on page load) 2,) 10 different quotes randomly fadeing in and out in random...
10
by: Sonoman | last post by:
Hi all: I am trying to write a simple program that simulates asking several persons their birth day and it counts how many persons are asked until two have the same birth day. The problem that I...
10
by: Ioannis Vranos | last post by:
I want to create some random numbers for encryption purposes, and i wonder if the following scheme makes it more hard to guess the underneath number generation pattern, than the plain use of...
13
by: quickcur | last post by:
Suppose I have a function rand() that can generate one integer random number between 0 and 100. Suppose also rand() is very expensive. What is the fastest way to generate 10 different random number...
4
by: Dimos | last post by:
Hello All, I need some help with random number generation. What I need exactly is: To create a few thousand numbers, decimal and integers, between 5 and 90, and then to export them as a...
21
by: chico_yallin | last post by:
I just wana make a random id number based on4 digits-for examples?? Thanks in Advance Ch.Yallin
8
by: Anil Gupte | last post by:
I had someone write a random number generator in C# (I am more of a VB programmer) and they came up with the following: public string GetRand(int count) { string number = ""; for (int i=0;...
16
by: jason.cipriani | last post by:
I am looking for a random number generator implementation with the following requirements: - Thread-safe, re-entrant. - Produces consistently reproducible sequences of psuedo-random numbers...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.