473,398 Members | 2,525 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,398 software developers and data experts.

How to generate random number between two numbers

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??
Sep 29 '08 #1
19 13634
Sanchit wrote:
I want to generate a randowm number between two numbers x and y i.e

int randomNoBetween(int x, int y);
The (I guess) simplest way to get a random number in the interval [0, n)
(that is, 0 inclusive, n exclusive) is (if n is small enough) probably
(rand() % n), which will however slightly favor smaller numbers.

I can't tell if there's any "consensus" on whether to use this method or
some more expensive (like floating point arithmetic) to do this.

With this method, it is trivial to write your function in question; this
is left as an exercise to you ;)

Daniel

--
Done: Arc-Bar-Cav-Rog-Sam-Val-Wiz
To go: Hea-Kni-Mon-Pri-Ran-Tou
Sep 29 '08 #2
On Sep 29, 2:43 pm, Daniel Kraft <d...@domob.euwrote:
Sanchit wrote:
I want to generate a randowm number between two numbers x and y i.e
int randomNoBetween(int x, int y);
See question 13.16 of the C-FAQ.
<http://c-faq.com/>
The (I guess) simplest way to get a random number in the interval [0, n)
(that is, 0 inclusive, n exclusive) is (if n is small enough) probably
(rand() % n), which will however slightly favor smaller numbers.
Yes, see question 13.18 of the aforementioned FAQ to learn why.
Sep 29 '08 #3
On Sep 29, 7:43*am, Daniel Kraft <d...@domob.euwrote:
Sanchit wrote:
I want to generate a randowm number between two numbers x and y i.e
int randomNoBetween(int x, int y);

The (I guess) simplest way to get a random number in the interval [0, n)
(that is, 0 inclusive, n exclusive) is (if n is small enough) probably
(rand() % n), which will however slightly favor smaller numbers.
You can eliminate the bias by computing the largest multiple of
RAND_MAX that's evenly divisible by n. Call this M. Then just throw
away random numbers until you get one in the range 0 to M-1. Call
this R. Then return R % n.

Sep 29 '08 #4
>I want to generate a randowm number between two numbers x and y i.e

Generating random numbers requires specialized hardware. Do you
want pseudo-random numbers instead? There's a big difference,
especially to those using cryptography.
>
int randomNoBetween(int x, int y);

Plz help
Is there any such function??
Generally, you can take whatever pseudo-random number generator you
have that generates numbers in a range you can't control, and use
algebra to transform that range into the one you want. Sometimes
this will result in inaccurate probability distribution.

Sep 29 '08 #5
On Sep 29, 11:36*pm, gor...@hammy.burditt.org (Gordon Burditt) wrote:
I want to generate a randowm number between two numbers x and y i.e

Generating random numbers requires specialized hardware. *Do you
want pseudo-random numbers instead? *There's a big difference,
especially to those using cryptography.
int randomNoBetween(int x, int y);
Plz help
Is there any such function??

Generally, you can take whatever pseudo-random number generator you
have that generates numbers in a range you can't control, and use
algebra to transform that range into the one you want. *Sometimes
this will result in inaccurate probability distribution.
I have to generate a pseudo random number
Oct 2 '08 #6
Sanchit <sa************@gmail.comwrites:
On Sep 29, 11:36*pm, gor...@hammy.burditt.org (Gordon "rude" Burditt) wrote:
[...]
>Generally, you can take whatever pseudo-random number generator you
have that generates numbers in a range you can't control, and use
algebra to transform that range into the one you want. *Sometimes
this will result in inaccurate probability distribution.

I have to generate a pseudo random number
You *have* to? Why?

Did you have a question beyond what you asked originally? Did the
extensive discussion and references in this thread not answer your
question?

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Oct 2 '08 #7
On 2 Oct, 07:19, Sanchit <sanchitgupt...@gmail.comwrote:
I have to generate a pseudo random number
rand()

--
Nick Keighley
Oct 2 '08 #8

"Sanchit" <sa************@gmail.comwrote in message
news:39**********************************@n38g2000 prl.googlegroups.com...
>I want to generate a randowm number between two numbers x and y i.e

int randomNoBetween(int x, int y);
Given a function random() which generates a (necessarily) pseudo-random
integer with enough bits for your purpose:

/* Return random number from x to y inclusive */
int randomNoBetween(int x, int y) {
return (random() %(y-x+1))+x;
}

You will have to find your own random(); I just use something like this:

#include <stdlib.h>

int random() {
return (rand()<<15) | rand();
}

--
Bartc

Oct 3 '08 #9
"Bartc" <bc@freeuk.comwrites:
"Sanchit" <sa************@gmail.comwrote in message
news:39**********************************@n38g2000 prl.googlegroups.com...
>>I want to generate a randowm number between two numbers x and y i.e

int randomNoBetween(int x, int y);

Given a function random() which generates a (necessarily)
pseudo-random integer with enough bits for your purpose:

/* Return random number from x to y inclusive */
int randomNoBetween(int x, int y) {
return (random() %(y-x+1))+x;
}

You will have to find your own random(); I just use something like this:

#include <stdlib.h>

int random() {
return (rand()<<15) | rand();
}
Eek! The general advice is to leave a PRNG alone unless you know it
has a fault and your fix is correct for it. I've seen more problems
caused by "fixed" PRNGs than by intrinsically bad ones.

The above is not a good idea. It has probable undefined behaviour (on
most systems) and will produce badly biased results if RAND_MAX is not
65535.

--
Ben.
Oct 3 '08 #10
"Ben Bacarisse" <be********@bsb.me.ukwrote in message
news:87************@bsb.me.uk...
"Bartc" <bc@freeuk.comwrites:
>You will have to find your own random(); I just use something like this:

#include <stdlib.h>

int random() {
return (rand()<<15) | rand();
}

Eek! The general advice is to leave a PRNG alone unless you know it
has a fault and your fix is correct for it. I've seen more problems
caused by "fixed" PRNGs than by intrinsically bad ones.

The above is not a good idea. It has probable undefined behaviour (on
most systems) and will produce badly biased results if RAND_MAX is not
65535.
Last check I checked, rand() only returned a 15-bit result. And just quickly
checking again the 3 compilers I use, they are still all 15-bits.

Still, perhaps that second rand() can be &-ed with 32767 just in case.

A RAND_MAX of 32767 is too low.

--
Bartc

Oct 3 '08 #11
"Bartc" <bc@freeuk.comwrites:
"Ben Bacarisse" <be********@bsb.me.ukwrote in message
news:87************@bsb.me.uk...
>"Bartc" <bc@freeuk.comwrites:
>>You will have to find your own random(); I just use something like this:

#include <stdlib.h>

int random() {
return (rand()<<15) | rand();
}

Eek! The general advice is to leave a PRNG alone unless you know it
has a fault and your fix is correct for it. I've seen more problems
caused by "fixed" PRNGs than by intrinsically bad ones.

The above is not a good idea. It has probable undefined behaviour (on
most systems) and will produce badly biased results if RAND_MAX is not
65535.
Correction to self: I meant 32767 and I think you got that.
Last check I checked, rand() only returned a 15-bit result. And just
quickly checking again the 3 compilers I use, they are still all
15-bits.
That does not mean the advice is good. Just say: "with my C lib
RAND_MAX is 32767 so I do..." and you won't get a comment (except the
one below). It looked like general advice and as such it us unwise.
Still, perhaps that second rand() can be &-ed with 32767 just in
case.
I would not do that. If the & is needed to avoid the bias of
overlapping bits then the whole construct is ill-advised.
A RAND_MAX of 32767 is too low.
I agree, but halving the period of a bad PRNG in exchange for doubling
the bits per call is not always a good idea. It may be worth it in
your case (I have no idea why you are doing it) but, again, it is not
really sound advice /in general/.

--
Ben.
Oct 3 '08 #12
In article <87************@bsb.me.uk>,
Ben Bacarisse <be********@bsb.me.ukwrote:
>Still, perhaps that second rand() can be &-ed with 32767 just in
case.
>I would not do that. If the & is needed to avoid the bias of
overlapping bits then the whole construct is ill-advised.
I disagree. If you have a source that provides at least 15 random
bits (which, modulo poor quality of implementation, rand() is
required to do), and you need some larger number of random bits,
then sticking together chunks of 15 bits is a reasonable approach.

You could be more sophisticated and examine RAND_MAX to see how many
bits you get, but it would be somewhat tedious especially as I don't
think it's guaranteed that RAND_MAX is of the form 2^n-1.

-- Richard
--
Please remember to mention me / in tapes you leave behind.
Oct 3 '08 #13
"Bartc" <bc@freeuk.comwrites:
"Ben Bacarisse" <be********@bsb.me.ukwrote in message
news:87************@bsb.me.uk...
>"Bartc" <bc@freeuk.comwrites:
>>You will have to find your own random(); I just use something like this:

#include <stdlib.h>

int random() {
return (rand()<<15) | rand();
}

Eek! The general advice is to leave a PRNG alone unless you know it
has a fault and your fix is correct for it. I've seen more problems
caused by "fixed" PRNGs than by intrinsically bad ones.

The above is not a good idea. It has probable undefined behaviour (on
most systems) and will produce badly biased results if RAND_MAX is not
65535.

Last check I checked, rand() only returned a 15-bit result. And just
quickly checking again the 3 compilers I use, they are still all
15-bits.
RAND_MAX must be at least 32767 (and at most INT_MAX). It's
2147483647 on two systems I just tried. (BTW, RAND_MAX is an
attribute of the runtime library, not of the compiler.)
Still, perhaps that second rand() can be &-ed with 32767 just in case.

A RAND_MAX of 32767 is too low.
If you mean it's too low for your purposes, I won't disagree, but it's
allowed by the standard.

Your random() function (note that there's a POSIX function by that
name, so you might want to pick something else), with the "&32767"
added, produces 30 bits of randomness. You might consider checking
whether RAND_MAX is big enough, and if so, just call rand() once:

int rand30(void)
{
#define BITS15 0x7fff
#define BITS30 0x3fffffff
#if RAND_MAX >= BITS30
return rand() & BITS30;
#else
return (rand() & BITS15) << 15 | (rand() & BITS15);
#endif
}

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Oct 3 '08 #14
ri*****@cogsci.ed.ac.uk (Richard Tobin) writes:
In article <87************@bsb.me.uk>,
Ben Bacarisse <be********@bsb.me.ukwrote:
>>Still, perhaps that second rand() can be &-ed with 32767 just in
case.
>>I would not do that. If the & is needed to avoid the bias of
overlapping bits then the whole construct is ill-advised.

I disagree. If you have a source that provides at least 15 random
bits (which, modulo poor quality of implementation, rand() is
required to do), and you need some larger number of random bits,
then sticking together chunks of 15 bits is a reasonable approach.
Oh sure. If you need more bits then shifting, masking and or-ing is
fine. It was the idea that bunging in a mask would fix the specific
code that prompted my comment. If the mask is needed then the code is
in danger of producing UB.
You could be more sophisticated and examine RAND_MAX to see how many
bits you get, but it would be somewhat tedious especially as I don't
think it's guaranteed that RAND_MAX is of the form 2^n-1.
No, but if you don't inspect RAND_MAX and make the code depend on it
in some way you are in danger of shifting too much.

--
Ben.
Oct 3 '08 #15
Bartc wrote:
"Ben Bacarisse" <be********@bsb.me.ukwrote:
.... snip ...
>
>The above is not a good idea. It has probable undefined
behaviour (on most systems) and will produce badly biased
results if RAND_MAX is not 65535.

Last check I checked, rand() only returned a 15-bit result. And
just quickly checking again the 3 compilers I use, they are still
all 15-bits.

Still, perhaps that second rand() can be &-ed with 32767 just in
case.

A RAND_MAX of 32767 is too low.
Then install a good random mechanism. For example, the source code
for cokusmt.h and cokusmt.c is included in my nmmalloc.zip package,
and implements the Mersenne twister. This package is in the public
domain, so you can use it freely. My (minor) corrections to make
it purely standard C coding have not been checked on systems with
longs larger than 32 bits, so such use is caught and signalled.
Nobody has checked it out in such a location yet.

See: <http://cbfalconer.home.att.net/download/nmalloc.zip>

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
Oct 3 '08 #16
In article <87************@bsb.me.uk>,
Ben Bacarisse <be********@bsb.me.ukwrote:
>You could be more sophisticated and examine RAND_MAX to see how many
bits you get, but it would be somewhat tedious especially as I don't
think it's guaranteed that RAND_MAX is of the form 2^n-1.
>No, but if you don't inspect RAND_MAX and make the code depend on it
in some way you are in danger of shifting too much.
You can rely on RAND_MAX being at least 32767, so if you only use
15 bits you don't have to inspect it.

-- Richard

--
Please remember to mention me / in tapes you leave behind.
Oct 4 '08 #17
CBFalconer <cb********@yahoo.comwrote:
Bartc wrote:
Still, perhaps that second rand() can be &-ed with 32767 just in
case.

A RAND_MAX of 32767 is too low.
_If_ your rand() is good enough (and there is no guarantee that it is),
you can simply get 30 bits of pseudo-randomness, even using the usual
15-bit rand(), with

long twice_rand(void)
{
return (rand()&32767)<<15 + rand()&32767;
}

and even more by repeating this method. However, I do not recommend
this.
Then install a good random mechanism. For example, the source code
for cokusmt.h and cokusmt.c is included in my nmmalloc.zip package,
and implements the Mersenne twister.
Neither do I recommend the MT for most people and most purposes. Yes, it
is very good, but it is also complex and uses a lot of state. And it's
quite slow, for a PRNG. In other words, if you're running an on-line
casino, it's not good enough (you want _real_ randomness for that); if
you're running nearly anything else, it's too good; AFAICT, the MT is
the thing for you only if you run Monte Carlo simulations of quantum or
astronomical systems.
For most people, I'd recommend using something simpler than MT, yet
better than the Standard example of rand() (which, remember, is a
_minimal_ implementation). For example, in the message to this newsgroup
with Message-ID <S%******************@news1.rdc1.fl.home.com(you
should be able to find it on any good news archive, and also on Google
Groups), George Marsaglia talks about a 32-bit-minus-one PRNG which is
not perfect, but very good for most uses, easy to implement, and quite
swift. It's simply this (with seed function added by me):

uint32_t seed=1; /* Must be a 32-bit, unsigned type. Can't be zero,
and won't ever reach zero through this PRNG. */

uint32_t threeshift_srand(const uint32_t newseed)
{
uint32_t oldseed=seed;

if (newseed)
seed=newseed;

return oldseed;
}

/* Returns a PRN between 0 and 2**32 - 1. */
uint32_t threeshift_rand(void)
{
seed^=seed<<13; seed^=seed>>17; seed^=seed<<5;
return seed-1;
}

Even if you don't use that PRNG, a search of posts to this group by
George Marsaglia will probably tell you more about PRNGs than the rest
of us put together could teach you.

Richard
Oct 7 '08 #18
Richard Bos wrote:
CBFalconer <cb********@yahoo.comwrote:
.... snip ...
>
>Then install a good random mechanism. For example, the source
code for cokusmt.h and cokusmt.c is included in my nmmalloc.zip
package, and implements the Mersenne twister.

Neither do I recommend the MT for most people and most purposes.
Yes, it is very good, but it is also complex and uses a lot of
state. And it's quite slow, for a PRNG. In other words, if you're
running an on-line casino, it's not good enough (you want _real_
randomness for that); if you're running nearly anything else,
it's too good; AFAICT, the MT is the thing for you only if you run
Monte Carlo simulations of quantum or astronomical systems.
Well, I suggest postponing worrying about speed until you find it
affects you. The system I recommended above is quite fast, but it
will occasionally take a few extra microsecs to prepare a new
batch. I have had no problems with it for many millions of calls.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
Oct 8 '08 #19
CBFalconer <cb********@yahoo.comwrote:
Richard Bos wrote:
CBFalconer <cb********@yahoo.comwrote:
Then install a good random mechanism. For example, the source
code for cokusmt.h and cokusmt.c is included in my nmmalloc.zip
package, and implements the Mersenne twister.
Neither do I recommend the MT for most people and most purposes.
Yes, it is very good, but it is also complex and uses a lot of
state. And it's quite slow, for a PRNG. In other words, if you're
running an on-line casino, it's not good enough (you want _real_
randomness for that); if you're running nearly anything else,
it's too good; AFAICT, the MT is the thing for you only if you run
Monte Carlo simulations of quantum or astronomical systems.

Well, I suggest postponing worrying about speed until you find it
affects you. The system I recommended above is quite fast, but it
will occasionally take a few extra microsecs to prepare a new
batch. I have had no problems with it for many millions of calls.
IYAM a PRNG which normally is fast enough, but on occasion takes a
measureable time extra, is worse than one which is always only a little
slow, though I'm sure that for some purposes it would be better. I agree
with your point about timing it, though; nevertheless, I still think
that for the vast majority of people, the MT is overkill, and they'd be
better served with something simpler.

Richard
Oct 9 '08 #20

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

Similar topics

2
by: vishal | last post by:
hi i want to generate a string which contains 5 characters and all 5 characters are randomly generated means it is not fixed that which string i will get after i execute function. so tell me...
3
by: vishal | last post by:
i want to generate a random number of a fixed length so how can i do this ?? i know some function which returns a single random character at a time but is there any built-in function which...
12
by: Sweety | last post by:
plz reply, thanks in advance. bye
4
by: fatimahtaher | last post by:
Hi, I am supposed to create a program that generates a random number and then asks the user to guess the number (1-100). The program tells the user if he guessed too high or too low. If he...
2
by: Man4ish | last post by:
How to generate random number in normal distribution without using any external library. I found few methods implementing it. But all use GSL or boost. I don't want to use any third party library....
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
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,...
0
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,...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
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...

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.