473,414 Members | 1,980 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,414 software developers and data experts.

random number

I want to get a random number between 0 and 1.
The following code works but it seems to me a litte
awkward. Is there a "better" solution.

double rnd;
int integerRnd;

srand(static_cast<unsigned>(time(NULL)));
for (int i = 0; i < 9; ++i) {
// rand() returns a value from 0 to 32767
rnd = 10000. / rand();
// integer part of quotient
integerRnd = rnd;
// every random number in the form of 0.xxx
rnd -= integerRnd;
cout << rnd << endl;
}
Jul 23 '05 #1
15 27272
Roman Töngi wrote:
I want to get a random number between 0 and 1.
The following code works but it seems to me a litte
awkward. Is there a "better" solution.


The usual way to reduce values in the range [0, n) to the range [0, 1)
is to divide by n+1. If you want 1 to be in the final range, divide by n
instead.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #2
Roman Töngi wrote:
I want to get a random number between 0 and 1.
The following code works but it seems to me a litte
awkward. Is there a "better" solution.
There are many solutions out there. Have you tried the web?
You don't say what distribution you need. For uniform one
you can simply scale the numbers you get from 'rand' function
(see comp.lang.c FAQ for the recommendations). For other
distributions there are other approaches. Again, the web is
your friend in that case.
[..]

Jul 23 '05 #3
Pete Becker wrote:
Roman Töngi wrote:
I want to get a random number between 0 and 1.
The following code works but it seems to me a litte
awkward. Is there a "better" solution.


The usual way to reduce values in the range [0, n) to the range [0, 1)
is to divide by n+1. If you want 1 to be in the final range, divide by n
instead.


Forgot to mention, the following comment:

// rand() returns a value from 0 to 32767

is incorrect. Some implementations of rand do that, others don't. Look
it up.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #4
> Forgot to mention, the following comment:

// rand() returns a value from 0 to 32767

is incorrect. Some implementations of rand do that, others don't. Look it
up.


I did. In my C++ implementation it is as noted.
Jul 23 '05 #5
Roman Töngi wrote:
I want to get a random number between 0 and 1.
The following code works but it seems to me a litte
awkward. Is there a "better" solution.

double rnd;
int integerRnd;

srand(static_cast<unsigned>(time(NULL)));
for (int i = 0; i < 9; ++i) {
// rand() returns a value from 0 to 32767
rnd = 10000. / rand();
// integer part of quotient
integerRnd = rnd;
// every random number in the form of 0.xxx
rnd -= integerRnd;
cout << rnd << endl;
}

From the rand() manpage:

<quote>

#include <stdlib.h>
Jul 23 '05 #6
Roman Töngi wrote:
I want to get a random number between 0 and 1.
The following code works but it seems to me a litte
awkward. Is there a "better" solution.

double rnd;
int integerRnd;

srand(static_cast<unsigned>(time(NULL)));
for (int i = 0; i < 9; ++i) {
// rand() returns a value from 0 to 32767
rnd = 10000. / rand();
// integer part of quotient
integerRnd = rnd;
// every random number in the form of 0.xxx
rnd -= integerRnd;
cout << rnd << endl;
}


If you want a uniform distribution, this code is broken. About 57.7%
of your random numbers are below 0.5 and about 42.3% are above.

You might want to look into the random number generator library from
boost.org.
Best

Kai-Uwe Bux
Jul 23 '05 #7
Roman Töngi wrote:

I did. In my C++ implementation it is as noted.


So you know your code will work as long as you don't use any other
implementation. <g> Use RAND_MAX. It expands to the right value on all
implementations.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #8
> If you want a uniform distribution, this code is broken. About 57.7%
of your random numbers are below 0.5 and about 42.3% are above.


How does it come to that percentage?
Jul 23 '05 #9
Larry I Smith wrote:

From the rand() manpage:

.
If you want to generate a random integer between 1 and 10, you
should always do it by using high-order bits, as in

j = 1 + (int) (10.0 * rand() / (RAND_MAX + 1.0));


However, this version introduces a different problem: it's not uniform,
even if rand is. For small ranges like 1..10 the nonuniformity isn't
noticeable, but for larger ones (i.e. 1..RAND_MAX/100) it's a definite
problem.

When producing floating point ranges this approach is okay, because the
values in the target range are dense enough that they'r e nearly
continuous. For integral ranges, though, you need a more sophisticated
technique. TR1 will do this, with std::tr1::uniform_int.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #10
Pete Becker wrote:
Larry I Smith wrote:

From the rand() manpage:

.
If you want to generate a random integer between 1 and 10, you
should always do it by using high-order bits, as in

j = 1 + (int) (10.0 * rand() / (RAND_MAX + 1.0));


However, this version introduces a different problem: it's not uniform,
even if rand is. For small ranges like 1..10 the nonuniformity isn't
noticeable, but for larger ones (i.e. 1..RAND_MAX/100) it's a definite
problem.

When producing floating point ranges this approach is okay, because the
values in the target range are dense enough that they'r e nearly
continuous. For integral ranges, though, you need a more sophisticated
technique. TR1 will do this, with std::tr1::uniform_int.


Yes, I understand the above, but does my suggestion

double d = d = (rand() / ((double)RAND_MAX));

Meet the OP's original need for a number between 0.0
and 1.0?

Regards,
Larry

--
Anti-spam address, change each 'X' to '.' to reply directly.
Jul 23 '05 #11
"Pete Becker" <pe********@acm.org> wrote in message
news:Hs********************@giganews.com...
Larry I Smith wrote:

From the rand() manpage:

.
If you want to generate a random integer between 1 and 10, you
should always do it by using high-order bits, as in

j = 1 + (int) (10.0 * rand() / (RAND_MAX + 1.0));


However, this version introduces a different problem: it's not uniform,
even if rand is. For small ranges like 1..10 the nonuniformity isn't
noticeable, but for larger ones (i.e. 1..RAND_MAX/100) it's a definite
problem.

When producing floating point ranges this approach is okay, because the
values in the target range are dense enough that they'r e nearly
continuous. For integral ranges, though, you need a more sophisticated
technique. TR1 will do this, with std::tr1::uniform_int.


For integral ranges, here is a function that takes care of the
non-uniformity issue by discarding the extra values:

int randN(int n)
{
const unsigned range = ((unsigned)(RAND_MAX)+1) / n;
int r;

do r = rand() / range;
while (r >= n);

return r;
}

I first heard about this method in a post by Andrew Koenig. The above
corrected version came in further discussions.

Note: Purists may want to use static_cast<unsigned> when casting :)

Ali

Jul 23 '05 #12
Roman Töngi wrote:
If you want a uniform distribution, this code is broken. About 57.7%
of your random numbers are below 0.5 and about 42.3% are above.


How does it come to that percentage?


Well, right of hand, there is no reason to expect a uniform distribution:
essentially you are starting with a uniformly distributed random variable
X in some interval [a,b], and then you turn this into

fractional part of ( 1/X )

Note that 1/X is not uniformly distributed in [1/b,1/a], and even if it
was taking fractional parts would not be unless both 1/b and 1/a are
an integer distance apart. Moreover, it is apparent that the resulting
distribution will depend heavily on the choice of the initial inverval
[a,b]. Thus, I expected a skewed distribution. Very likely it has several
bumps (I would expect one for each unit interval in [1/b,1/a]). Also the
distribution is probably not easy to describe and analyze theoretically.

As for the percentages, I just ran several experiments (drawing about
1.000.000 instances each) and counted. The numbers I gave are just results
of these experiments.
Best

Kai-Uwe Bux
Jul 23 '05 #13

Pete Becker wrote:
When producing floating point ranges this approach is okay, because the values in the target range are dense enough that they'r e nearly
continuous. For integral ranges, though, you need a more sophisticated technique. TR1 will do this, with std::tr1::uniform_int.

Or if you don't have std::tr1::uniform_int use boost::uniform_int. For
a better random numbers library check out boost.random

Jul 23 '05 #14
Larry I Smith wrote:
Pete Becker wrote:

When producing floating point ranges this approach is okay, because the
values in the target range are dense enough that they'r e nearly
continuous. For integral ranges, though, you need a more sophisticated
technique. TR1 will do this, with std::tr1::uniform_int.

Yes, I understand the above, but does my suggestion

double d = d = (rand() / ((double)RAND_MAX));

Meet the OP's original need for a number between 0.0
and 1.0?


As I said, "When producing floating point ranges this approach is okay..."

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Jul 23 '05 #15
"Larry I Smith" wrote:

If you want to generate a random integer between 1 and 10, you
should always do it by using high-order bits, as in

j = 1 + (int) (10.0 * rand() / (RAND_MAX + 1.0));

and never by anything resembling

j = 1 + (rand() % 10);

(which uses lower-order bits).


This is certainly true of linear congruential PRNGs (such as [usually] the standard library rand()), where lower-order
bits are known to be rather non-random. However, to what extent does this hold for other PRNGs such as the Mersenne
Twister, lagged Fibonacci, etc. which one would expect to have more random low bits?

--
Lionel B
Jul 23 '05 #16

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

Similar topics

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...
4
by: Jack | last post by:
I have two files: sort_comparison.c++ my_sort.h sort_comparison.c++ calls this code in my_sort.h: void my_sort::fillArray(int arr,int n) { // const int random_number_range=1000000;
70
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...
10
by: Johnny Snead | last post by:
Hey guys, Need help with this random sort algorithm private void cmdQuestion_Click(object sender, System.EventArgs e) { Random rnd = new Random(); //initialize rnd to new random object...
5
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...
8
by: Daniel | last post by:
Hey guys Using Random(), how random is it, is it possible to be predicted? I have a requirement for a very good random number generator. I was doing something such as: Random randomSeed = new...
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...
13
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,...
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;...
2
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...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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...
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
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...
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.