473,779 Members | 2,083 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can get random number in your range

Dear all,

I found function rand(), it can create random number but this function
can not define the range of number which I want to get it, such as, I
want to get random number in the range from 0 to 100 [0-100].

Please help me,

Many thanks,

Jul 27 '07 #1
7 2783
On 2007-07-27 09:38, bipi <nh*******@gmai l.comwrote:
I found function rand(), it can create random number but this function
can not define the range of number which I want to get it, such as, I
want to get random number in the range from 0 to 100 [0-100].
See the FAQ, question 13.16.

hp
--
_ | Peter J. Holzer | I know I'd be respectful of a pirate
|_|_) | Sysadmin WSR | with an emu on his shoulder.
| | | hj*@hjp.at |
__/ | http://www.hjp.at/ | -- Sam in "Freefall"
Jul 27 '07 #2
In article <ln************ @nuthaus.mib.or g>,
Keith Thompson <ks***@mib.orgw rote:
>Ben Bacarisse also made a good point about another problem with using
one result from rand() to generate one number is a specified range.
If there are, for example, 32768 possible results (RAND_MAX==3276 7),
and you want numbers in the range 0..99, you can't possibly produce a
uniform distribution, because 32768 is not a multiple of 100.
Or as I had already written in the random number speed thread a
couple of days ago,

"After that... find some power of 2 that is "just a bit" above a
multiple of r (minimize the difference between the power of 2
and the multiple), mask off that many bits from the returned
random number, then reject the result if it is in the upper portion
of the range (between the last full multiple and 2**N - 1)."

I didn't specifically speak of bias the way Ben did, but that
bias is the reason for the stated algorithm.
--
Okay, buzzwords only. Two syllables, tops. -- Laurie Anderson
Jul 27 '07 #3
ro******@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes:
In article <ln************ @nuthaus.mib.or g>,
Keith Thompson <ks***@mib.orgw rote:
>>Ben Bacarisse also made a good point about another problem with using
one result from rand() to generate one number is a specified range.
If there are, for example, 32768 possible results (RAND_MAX==3276 7),
and you want numbers in the range 0..99, you can't possibly produce a
uniform distribution, because 32768 is not a multiple of 100.

Or as I had already written in the random number speed thread a
couple of days ago,

"After that... find some power of 2 that is "just a bit" above a
multiple of r (minimize the difference between the power of 2
and the multiple), mask off that many bits from the returned
random number, then reject the result if it is in the upper portion
of the range (between the last full multiple and 2**N - 1)."

I didn't specifically speak of bias the way Ben did, but that
bias is the reason for the stated algorithm.
I think for best effect (fewest rejected random numbers), you'd want
to miminize the *ratio* of the chosen power of 2 and a multiple of the
size of your range, not the difference.

Using a power of 2, I think, makes part of the operation quicker (you
can use bitwise operations rather than division), but I think that by
ignoring powers of 2 you can reject fewer of the input random numbers.

I think you can avoid rejecting *any* input random numbers at the
expense of some fairly heavy calculations. For example, if your
desired range has 100 elements, you can treat a sequence of, say, 1000
16-bit numbers as a single, very large, base-100 number, and grab one
"digit" at a time. Generalizing this to arbitrarily long sequences is
likely to require operations on arbitrarily large integer (bignums),
and will be worthwhile only if the input random numbers are
*extremely* expensive, or if you absolutely can't afford to reject too
many in a row. But for such an application, it would probably be much
easier to write your own random number generator in the first place.

If RAND_MAX+1 is a multiple of the number of elements in your desired
range, all these problems go away.

--
Keith Thompson (The_Other_Keit h) 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."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jul 27 '07 #4
On Jul 27, 3:07 am, "Peter J. Holzer" <hjp-usen...@hjp.atw rote:
On 2007-07-27 09:38, bipi <nh.tru...@gmai l.comwrote:
I found function rand(), it can create random number but this
function can not define the range of number which I want to get it,
such as, I want to get random number in the range from 0 to 100
[0-100].

See the FAQ, question 13.16.
The FAQ is deceptive and incomplete on this issue (and what the hell
is drand48?). You can get a better explanation here:

http://www.pobox.com/~qed/random.html

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

Aug 2 '07 #5
Keith Thompson <ks***@mib.orgw rites:
Ben Bacarisse <be********@bsb .me.ukwrites:
>Army1987 <ar******@NOSPA M.itwrites:
<snip>
>>This is already pointed out in the Web version of the FAQ.
http://www.c-faq.com/lib/randrange.html

I can't find it. I am happy to assume it is me and leave it at that.
It is not a major issue, so if it is covered somewhere, that is more
than adequate.

It's covered in the cited web page (which is question 13.16 of the FAQ):

When N is close to RAND_MAX,...
So it is. Must pay more attention.

--
Ben.
Aug 2 '07 #6
we******@gmail. com writes:
On Jul 27, 3:07 am, "Peter J. Holzer" <hjp-usen...@hjp.atw rote:
>On 2007-07-27 09:38, bipi <nh.tru...@gmai l.comwrote:
I found function rand(), it can create random number but this
function can not define the range of number which I want to get it,
such as, I want to get random number in the range from 0 to 100
[0-100].

See the FAQ, question 13.16.

The FAQ is deceptive and incomplete on this issue
How so?
(and what the hell
is drand48?).
That's answered in question 13.21, which question 13.16 directly
refers to.
You can get a better explanation here:

http://www.pobox.com/~qed/random.html
You raise 3 major points on that page.

1. If the desired range does not divide the range of values returned
by rand() a bias is introduced. FAQ 13.16 directly addresses that.

2. The quality of rand() is often not very good. FAQ 13.16 also
directly addresses that.

3. There are problems if the desired range is wider than RAND_MAX. I
think that's a valid criticism, though it certainly doesn't justify
using the word "deceptive" . (And in this particular context, the OP
wanted range of 0..100, and RAND_MAX is guaranteed to be at least
32767.)

Your page appears to contain a lot of good information, and I hope to
have the time to read the whole thing at some point, but it's probably
more than would be appropriate for the clc FAQ. Adding a pointer to
your page to the "additional links" page
<http://www.c-faq.com/lib/sd15.htmlmight be a good idea.

Perhaps the FAQ has been updated since the last time you read it?

--
Keith Thompson (The_Other_Keit h) 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."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 2 '07 #7
we******@gmail. com wrote:
If you know anything about computer graphics; using a small state
rand() successively is like using (stochastic) dithering for images,
while using a large state rand() is like having truly higher
resolution. Having the higher resolution is generally better than
dithering which is basically trying to gloss over the fundamental
weakness of having lower resolution.
<ot>
I know something about graphics, and this analogy misses the mark.

Higher resolution with uniform samples is like a bad PRNG with lots of
bits. Stochastic sampling at lower resolution is like a good PRNG with
fewer bits. Uniform sampling produces aliasing; higher resolution just
changes the artifact wavelengths. Stochastic sampling randomizes (!)
the unavoidable error of discrete sampling, trading aliasing for much
less visually objectionable noise.

They aren't mutually exclusive, either. Just like you'd want your PRNG
with lots of bits to be good, you can stochastically sample at high
resolution. But for CG, if I have to choose, I'll take sampling quality
over raw resolution.

See

http://graphics.pixar.com/StochasticSampling/paper.pdf

So I think you need a different analogy.
</ot>

- Ernie http://home.comcast.net/~erniew
Aug 2 '07 #8

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

Similar topics

8
2478
by: Aaron | last post by:
I need some help writing this function the function returns a list of random non-duplicate integers in a string, 1 parameter indicating the maximum range. string randGen(int maxRange) maxRange=1000 the output would be:
11
2899
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 between 0 and 100? (call rand() only 10 times...) Thanks, qq
70
6285
by: Ben Pfaff | last post by:
One issue that comes up fairly often around here is the poor quality of the pseudo-random number generators supplied with many C implementations. As a result, we have to recommend things like using the high-order bits returned by rand() instead of the low-order bits, avoiding using rand() for anything that wants decently random numbers, not using rand() if you want more than approx. UINT_MAX total different sequences, and so on. So I...
4
6654
by: Jonathan Burd | last post by:
Greetings everyone, Here is a random string generator I wrote for an application and I'm wondering about the thread-safety of this function. I was told using static and global variables cause potential problems for thread-safety. So far, I'm only confused. I need a proper explanation for the concept so I can understand how to write thread-safe functions in the future. My apologies for posting a long routine.
36
6004
by: Michael B Allen | last post by:
Someone once posted the following macro on clc: #define randint(a,b) (a)+(((b)-(a)+1)*(float)rand()/RAND_MAX) Unfortunately it's flawed. If rand() returns RAND_MAX the result can be one larger than b. So can someone provide a *proper* macro (or function) that returns a random integer between (actually in) a range of values? For example randint(0, 999) could return:
5
3353
by: Peteroid | last post by:
I know how to use rand() to generate random POSITIVE-INTEGER numbers. But, I'd like to generate a random DOUBLE number in the range of 0.0 to 1.0 with resolution of a double (i.e., every possible double value in the range could come up with equal probability). I'd also like to be able to seed this generator (e.g., via the clock) so that the same sequence of random values don't come up every time. Anybody have an easy and fast...
3
24549
by: JoelPJustice | last post by:
I am working through a VBA book by myself to help and try and improve my skills. However, the book does not give you solutions to certain problems. I have worked through this problem up until bullet point 3. Here is the code I came up with up until now. Function RandomNormal(Mean As Double, StdDev As Double) As Double Application.Volatile Randomize RandomNormal = (StdDev * Sqr(-2 * Log(Rnd)) * Cos(2 * 3.141596 * Rnd)) + Mean End...
13
2815
by: Peter Oliphant | last post by:
I would like to be able to create a random number generator that produces evenly distributed random numbers up to given number. For example, I would like to pick a random number less than 100000, or between 0 and 99999 (inclusive). Further, the I want the range to be a variable. Concretely, I would like to create the following method: unsigned long Random( unsigned long num )
2
5479
by: alishaikhji | last post by:
I am working on a program which will need several different integer and float random numbers at different stages, for example: - At one point, I need a random number (float) in the range 0.1 to 10.0 - At one point, I need a random number (float) in the range 0.5 to 1.5 - At one point, I need a random number (float) in the range 0.3 to 3.0 - At one point, I need a random number (float) in the range 0.1 to 10.0 Also, I need to make it sure...
0
9633
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, 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...
0
9474
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10305
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...
1
10074
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,...
1
7483
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
6724
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
5373
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5503
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2867
bsmnconsultancy
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...

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.