473,767 Members | 2,131 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to generate random numbers in C

I need to generate two uniform random numbers between 0 and 1 in C ?
How to do it ?

I looked into rand function where you need to #define RAND_MAX as 1
but will this rand function give me uniformly distributed and unique
numbers ?
Apr 11 '08
24 7232
"Malcolm McLean" <re*******@btin ternet.comwrite s:
"pereges" <Br*****@gmail. comwrote in message news:
>>I need to generate two uniform random numbers between 0 and 1 in C ?
How to do it ?

I looked into rand function where you need to #define RAND_MAX as 1
but will this rand function give me uniformly distributed and unique
numbers ?
No, defining RAND_MAX as something else won't help. All it will do is
make the identifier useless in the rest of your program, without
touching the random number generator. Strictly it is UB in case
RAND_MAX appears in some standard library macro or other.

This is the generally accpeted way to do it
#define uniform() (rand() / (RAND_MAX + 1.0))
#define rnd(x) ( (x) * uniform() )

we add 1.0 to make rand() never return exactly unity, so rnd() is
always in the range 0 to x-1.
rnd(m) can be much closer to m than m-1. Did you mean:

#define rnd(x) ((int)((x) * uniform()))

perhaps? The OP wanted numbers between 0 and 1 so your uniform() is
sufficient if they mean doubles in [0,1).

--
Ben.
Jun 27 '08 #11
If you try to offer casino gambling games (e.g. craps, blackjack,
roulette, etc.) for real money using pseudo-random numbers, you're
going to lose.

There is no mathematical basis for this general statement, however,
there have been cases where people caught on to the sequence coming
from a poorly- or non-reseeded pseudo-random number generator
in a casino game and won hundreds of $thousands before the
casino realized their error...
My statement is more based on economics and psychology than
mathematics. If there's enough to gain, people will go to great
lengths to break your scheme, including stealing a machine (or
BUYING one) and taking it apart, bribing employees or ex-employees
to get source code and procedures, dedicating huge amounts of donated
CPU time under the guise of searching for aliens or a cure for
cancer, etc.

A really clever crack will not take so much in winnings that the
casino realizes it immediately, but will take less but over a longer
period of time.

Jun 27 '08 #12

"Ben Bacarisse" <be********@bsb .me.ukwrote in message
news:87******** ****@bsb.me.uk. ..
"Malcolm McLean" <re*******@btin ternet.comwrite s:
>"pereges" <Br*****@gmail. comwrote in message news:
>>>I need to generate two uniform random numbers between 0 and 1 in C ?
How to do it ?

I looked into rand function where you need to #define RAND_MAX as 1
but will this rand function give me uniformly distributed and unique
numbers ?
No, defining RAND_MAX as something else won't help. All it will do is
make the identifier useless in the rest of your program, without
touching the random number generator. Strictly it is UB in case
RAND_MAX appears in some standard library macro or other.

This is the generally accpeted way to do it
#define uniform() (rand() / (RAND_MAX + 1.0))
#define rnd(x) ( (x) * uniform() )

we add 1.0 to make rand() never return exactly unity, so rnd() is
always in the range 0 to x-1.

rnd(m) can be much closer to m than m-1. Did you mean:

#define rnd(x) ((int)((x) * uniform()))

perhaps? The OP wanted numbers between 0 and 1 so your uniform() is
sufficient if they mean doubles in [0,1).
That would be fine if int was 64 bits :-(

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Jun 27 '08 #13
In article <IA************ ********@bgtnsc 04-news.ops.worldn et.att.net>,
Bill Reid <ho********@hap pyhealthy.netwr ote:
>In a fair game, the player with the biggest house money volume wins.
>Oh, a "fair game"...who the hell offers a "fair game"? In any event,
it's irrelevant, because the actual most important factor (to the extent
that we indulge in the pointless semantics of pronouncing a "most
important factor") is the "expectatio n" of the game.
Actually, you can reliably win against poor odds if you have unlimited
resources and your opponent is required to accept your bets. Decide
how much you want to win. Bet enough to make that if you win. If you
do, quit. If you don't, bet enough to win back your losses plus your
desired win. If you can continue making bets in this manner, you will
eventually win, no matter how poor the odds.

In practice, you can't do this, because your resources are limited
compared to the Casino's. If they weren't, they would eventually
refuse your bet.

-- Richard
--
:wq
Jun 27 '08 #14

Gordon Burditt <go***********@ burditt.orgwrot e in message
news:T7ydnSMQJK BSnJzVnZ2dnUVZ_ sytnZ2d@interne tamerica...
If you try to offer casino gambling games (e.g. craps, blackjack,
roulette, etc.) for real money using pseudo-random numbers, you're
going to lose.
There is no mathematical basis for this general statement, however,
there have been cases where people caught on to the sequence coming
from a poorly- or non-reseeded pseudo-random number generator
in a casino game and won hundreds of $thousands before the
casino realized their error...

My statement is more based on economics and psychology than
mathematics. If there's enough to gain, people will go to great
lengths to break your scheme,
There's a limit to greed; just because somebody offers $1trillion
to run a mile in one second doesn't mean anybody is ever going
to be able to do it, no matter how motivated they are and how
hard they try.
including stealing a machine (or
BUYING one) and taking it apart, bribing employees or ex-employees
to get source code and procedures, dedicating huge amounts of donated
CPU time under the guise of searching for aliens or a cure for
cancer, etc.
Sure, this all happens now, and has always happened. Back
when I used to consult for the electronic slot machine and lottery
equipment makers, a popular method of getting money from the
machines was to zap them with about a zillion volts, hopefully
sometimes causing the CPU to fritz out and activate the hopper
dump solenoid and dump the coins in the hopper into the "loud bowl".
Then they'd scoop up as many as they could and try to hit the
doors before security locked them (they were in most cases
already detected and being tracked by security cameras
the moment the coins dropped).

A slightly more sophisticated method involved an operation
using a small drill and a procedure not unlike othroscopic
surgery to trigger a hopper dump; in any event, they still
couldn't fake the internal sequence of microprocessor events
that had to occur and were always recorded that were evidence
of a genuine jackpot, along with those omnipresent security
cameras...

Guys who REALLY knew the machines could even have
a whole set of fake EEPROMs ready to install in seconds
after they jimmied open the door; but seriously, wouldn't
it just be easier to get a friggin' job?
A really clever crack will not take so much in winnings that the
casino realizes it immediately, but will take less but over a longer
period of time.
Oh, they'll figure it out eventually, but the problem will still
be to predict a series of pseudo-random numbers seeded from
some split-second event at pseudo-random times...this would
be tough enough under the best of circumstances, and in
a casino environment, purt near impossible, even WITH
"inside information"...

---
William Ernest Reid

Jun 27 '08 #15
In article <Hh************ *********@bgtns c04-news.ops.worldn et.att.net>,
Bill Reid <ho********@hap pyhealthy.netwr ote:
>And no, not even with "unlimited resources", because "unlimited
resources" mean infinity bets and thus, INFINITY LOSSES,
I suggest you learn some mathematics before you rant in future.
All the bets involved are finite.

-- Richard
--
:wq
Jun 27 '08 #16
On Apr 11, 12:20*pm, gordonb.k5...@b urditt.org (Gordon Burditt) wrote:
I need to generate two uniform random numbers between 0 and 1 in C ?

Computers do not generate truly random numbers without hardware support.
Some techniques include the detection of radioactive decay and thermal
noise from a reverse-biased diode. *There is some belief that there
is randomness in the timing (say, down to picoseconds) of keystrokes,
although I don't think anyone has managed to tie human typing to quantum
effects yet. *Some CPU chips have hardware for random number generation
on them.

You may want pseudo-random numbers. *In cryptography, random numbers
are very important and the difference between pseudo-random numbers
and real random numbers used in encryption may get you killed as a
spy.

If you try to offer casino gambling games (e.g. craps, blackjack,
roulette, etc.) for real money using pseudo-random numbers, you're
going to lose.

rand() returns the same sequence of numbers each time the program
starts up unless you call srand() with a different seed value from
the last time. *Seed values are commonly derived from the time and/or
process ID (but NOT in applications where real random numbers are needed,
like gambling or cryptography: *32 bits of randomness isn't enough, and
a poor seed can cripple a good random number generator).
How to do it ?

There are better pseudo-random number generators than rand().
These have the disadvantage that they are not included in all C
libraries.
I looked into rand function where you need to #define RAND_MAX as 1

You do not get to redefine RAND_MAX. *Also, the return type of rand()
is int, so don't expect any values where 0 < rand() < 1 . *If RAND_MAX
were 1 (not allowed by the standard) all you would get is 0 and 1.
but will this rand function give me *uniformly distributed and unique
numbers ?

Consider using algebra. *rand() returns [0, RAND_MAX]. *You want
numbers between 0.0 and 1.0 including both endpoints. *Or is that just
including 0.0 but not 1.0? *Consider what these might give you:

* * * * ((double)rand() )/RAND_MAX
or
* * * * ((double)rand() )/(RAND_MAX+1)
What' the difference between random numbers and pseudo-random numbers?
Jun 27 '08 #17

Richard Tobin <ri*****@cogsci .ed.ac.ukwrote in message
news:ft******** ***@pc-news.cogsci.ed. ac.uk...
In article <Hh************ *********@bgtns c04-news.ops.worldn et.att.net>,
Bill Reid <ho********@hap pyhealthy.netwr ote:
And no, not even with "unlimited resources", because "unlimited
resources" mean infinity bets and thus, INFINITY LOSSES,

I suggest you learn some mathematics before you rant in future.
"The ironing is delicious" - Bart Simpson
All the bets involved are finite.
Which, according to you, require "unlimited resources"...we
can put Las Vegas out of business, as long as we make a "finite"
series of bets with an infinite amount of money...you're a genius!!!

But it's like I've said before...you guys have GOT to stick to
the return value of main() because everything else on planet
Earth is just too complicated for you...

---
William Ernest Reid

Jun 27 '08 #18
Chad wrote, On 13/04/08 18:22:

<snip>
What' the difference between random numbers and pseudo-random numbers?
psueudo-random numbers are numbers that look random (for some definition
of look random) but are really following some sequence (and this, by the
definition of C, includes all implementations of rand()) where as random
numbers really are random.

A quick search on Google will give you a lot more information on pseudo
random numbers.
--
Flash Gordon
Jun 27 '08 #19
In article <66************ **@mid.individu al.net>
Ian Collins <ia******@hotma il.comwrote:
>Why would you attempt to redefine RAND_MAX? ...
Not everyone starts out with the right mental model of RAND_MAX.

It may help to think of RAND_MAX as if it were a highway sign,
telling you how far away the next town or exit is. If you stop
your car, walk up to the sign, paint out the original number, and
then paint in a "1", will the next town or exit move to just 1 mile
(or 1 kilometer) away? :-)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: gmail (figure it out) http://web.torek.net/torek/index.html
Jun 27 '08 #20

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

Similar topics

2
8288
by: Laphan | last post by:
Hi All This is a strange request, but I just cannot fathom how to do it. In theory the requirement is very basic, but in practise its a noodle!! I have 10 team names like so: Team A Team B
14
9904
by: Anthony Liu | last post by:
I am at my wit's end. I want to generate a certain number of random numbers. This is easy, I can repeatedly do uniform(0, 1) for example. But, I want the random numbers just generated sum up to 1 . I am not sure how to do this. Any idea? Thanks.
12
5229
by: Jim Michaels | last post by:
I need to generate 2 random numbers in rapid sequence from either PHP or mysql. I have not been able to do either. I get the same number back several times from PHP's mt_rand() and from mysql's RAND(). any ideas? I suppose I could use the current rancom number as the seed for the next random number. but would that really work?
9
9956
by: MyInfoStation | last post by:
Hi all, I am a newbie to Python and would like to genereate some numbers according to geometric distribution. However, the Python Random package seems do not have implemented functionality. I am wondering is there exist any other libraries that can do this job? Thanks a lot, Da
6
2780
by: Anamika | last post by:
I am doing a project where I want to generate random numbers for say n people.... These numbers should be unique for n people. Two people should not have same numbers.... Also the numbers should not be repeted.. Do anyone have some nice algorithm for that? Or anyone can suggest me any type of book or site for that purpose?
20
7855
by: jjmillertime | last post by:
I'm new so i apologize if this is in the wrong spot. I'm also new to programming in C and i've been searching for quite a while on how to create a program using C that will generate two random numbers, multiply them, and ask you for the result. It also needs to have four responses for both right and wrong answers and should print them randomly as well. The program should use at least 2 functions. Any help would be greatly appreciated. ...
9
6608
by: Chelong | last post by:
Hi All I am using the srand function generate random numbers.Here is the problem. for example: #include<iostream> #include <time.h> int main() {
19
13678
by: Sanchit | last post by:
I want to generate a randowm number between two numbers x and y i.e int randomNoBetween(int x, int y); Plz help Is there any such function??
0
10169
Oralloy
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...
0
10013
jinu1996
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...
1
9960
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,...
0
9841
tracyyun
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...
1
7383
isladogs
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...
0
6655
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5424
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3930
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3533
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.