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

RAND between 0 and 1

Hi all,

I think this has been posted many times.. but I tried several recipes
for obtaining a random number between [0,1], but I can't make them work.

So, does anyone know how to generate random number x, for 0<= x <=1??

Thanks,

FBM

That's what I got.......

float rndm = (float) (rand() / RAND_MAX);

and I tried also

float rndm = (float) (rand() % 2);

with no success...
Nov 15 '05 #1
11 80543
Fernando Barsoba wrote:
I think this has been posted many times.. but I tried several recipes
for obtaining a random number between [0,1], but I can't make them work.

So, does anyone know how to generate random number x, for 0<= x <=1??

Question 13.16 in the FAQ: http://www.eskimo.com/~scs/C-faq/q13.16.html.
Also check out the questions in the vicinity.

S.
Nov 15 '05 #2
On Thu, 29 Sep 2005 03:51:13 GMT, Fernando Barsoba
<fb******@verizon.net> wrote in comp.lang.c:
Hi all,

I think this has been posted many times.. but I tried several recipes
for obtaining a random number between [0,1], but I can't make them work.
Define what you mean by now working.
So, does anyone know how to generate random number x, for 0<= x <=1??

Thanks,

FBM

That's what I got.......

float rndm = (float) (rand() / RAND_MAX);
Aha! Integer division! RAND_MAX is a macro that evaluates to a
numeric literal of type int. rand() returns a value that is of type
int. The result of dividing an int by an int is an int quotient, with
any remainder discarded. Casting the result to a float after the
integer division/truncation does not bring the fractional part back.
and I tried also

float rndm = (float) (rand() % 2);

with no success...


In the future, don't just say "doesn't work". Describe the results
you are getting. It makes no difference in this case, but very often
it does when someone is trying to locate the cause of your problem.

In any case, you need to cast one or the other of the operands of the
division to a float. This will cause promotion of the other operand
to a float. Then a float division will be performed on the two float
values, yielding a float result. In any case, you do not need the
cast on the assignment to a float, that conversion is automatic and
the cast operator does absolutely nothing.

float rndm = rand()/(float)RAND_MAX;

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 15 '05 #3

"Fernando Barsoba" <fb******@verizon.net> wrote
float rndm = (float) (rand() / RAND_MAX);

This is the way to do it. However you need to cast to a float first,
otherwise you will get an integer division.
Incidentally it is traditional to divide by RAND_MAX plus one, because a lot
of algorithms don't work as nicely when a random number on the interval 0-1
is exactly unity.
Nov 15 '05 #4
Fernando Barsoba wrote:
Hi all,

I think this has been posted many times.. but I tried several recipes
for obtaining a random number between [0,1], but I can't make them work.

So, does anyone know how to generate random number x, for 0<= x <=1??


You could check the FAQ before posting. Or I could spoonfeed you:

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

inline double closed_interval_rand(double x0, double x1)
{
return x0 + (x1 - x0) * rand() / ((double) RAND_MAX);
}

int main(void)
{
int pass;
srand(time(0));
for (pass = 0; pass < 10; pass++)
printf("%d: %g\n", pass, closed_interval_rand(0, 1));
return 0;
}

[output for one invocation]
0: 0.589319
1: 0.108868
2: 0.13723
3: 0.575189
4: 0.444024
5: 0.657485
6: 0.83961
7: 0.00479315
8: 0.849472
9: 0.740225

Nov 15 '05 #5
Is there any reason to avoid using this:

srand(time(0));

float random_number = rand();

Nov 15 '05 #6
Why is it better:

rand() / (RAND_MAX / N + 1)

than:

srand(time(0));
rand() % N;

Nov 15 '05 #7
Thanks to all for your postings. I meant to say that the result was
0.0.. but now I solved it thanks to your comments.
float rndm = (rand() / (float)RAND_MAX);

The srand(time(null)) I used it to obtain a non-predictable random
number generator (if i say it correctly..)

cheers,

FBM
Fernando Barsoba wrote: Hi all,

I think this has been posted many times.. but I tried several recipes
for obtaining a random number between [0,1], but I can't make them work.

So, does anyone know how to generate random number x, for 0<= x <=1??

Thanks,

FBM

That's what I got.......

float rndm = (float) (rand() / RAND_MAX);

and I tried also

float rndm = (float) (rand() % 2);

with no success...

Nov 15 '05 #8
"Gaijinco" <ga******@gmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Why is it better:

rand() / (RAND_MAX / N + 1)

than:

srand(time(0));
rand() % N;


The problem with random integers in a desired interval is that when you
start doing tricks like the above the distribution ceases to be uniform.
Here's an example revealing this problem:

#include <stdio.h>

#define MY_RAND_MAX 15 // my RAND_MAX for myrand()
#define N 10 // the N in myrand()%N
#define M 1000 // iterations count

// My fake rand() function,
// mimicking uniform distribution.
// THIS IS A BAD random generator,
// BUT A GOOD means to show the problem
// of the rand()%N approach to generate
// uniformly distributed numbers in the range
// smaller than [0,RAND_MAX].
int myrand()
{
static int seed = 0;
int res = seed;
// generate numbers in the range [0,MY_RAND_MAX]
// like so: 0,1,2,...,MY_RAND_MAX-1,MY_RAND_MAX,0,1,2,...
if (++seed > MY_RAND_MAX)
seed = 0;
return res;
}

int main()
{
int i;
int aCnt[N];

// zero up counters of each of the numbers
// that will be generated at random:
for (i=0; i<N; i++)
aCnt[i] = 0;

// generate numbers at random and count
// how many time each of them was generated:
for (i=0; i<M; i++)
aCnt[myrand()%N]++;

// print out the statistics:
printf ("Statistics:\n"
"+--------+-------------------+\n"
"| Number | Times Encountered |\n"
"+--------+-------------------+\n");
for (i=0; i<N; i++)
printf ("| %-6d | %-17d |\n", i, aCnt[i]);
printf ("+--------+-------------------+\n");

return 0;
}
Alex
Nov 15 '05 #9
Fernando Barsoba <fb******@verizon.net> writes:
Thanks to all for your postings. I meant to say that the result was
0.0.. but now I solved it thanks to your comments.
>> float rndm = (rand() / (float)RAND_MAX);


The srand(time(null)) I used it to obtain a non-predictable random
number generator (if i say it correctly..)


Please don't top-post; your response goes below any quoted text, which
should be trimmed down to what's relevant.

I think you mean srand(time(NULL)). This isn't bad, but it does
assume some things that aren't guaranteed by the standard. The time()
function returns a result of type time_t, which is an arithmetic type
capable of representing times. It could legally be a floating-point
value in the range 0.0..1.0, which would result in always passing 0 to
srand(), which would always give you the same sequence of numbers. I
don't know of any implementations that behave this way, so that's
probably fairly safe. (srand() takes an argument of type unsigned
int, so the conversion from time_t isn't going to be a problem.)

Another problem is that the standard rand() function is often poorly
implemented. If the security of your system depends on high-quality
unpredictable random numbers (e.g., if you're doing cryptography), you
should find some system-specific random number generator. In
particular, using time() to seed the generator is good enough for some
applications, but could make it possible for an adversary to predict
the behavior of your program if he can guess what time it was started.

--
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.
Nov 15 '05 #10
<posted & mailed>

float r = ((float) rand()) / RAND_MAX;

.... rand() returns and integer that is equal to or less than RAND_MAX.
Dividing an integer by an integer larger than it yields 0, if the same, 1.

Fernando Barsoba wrote:
Hi all,

I think this has been posted many times.. but I tried several recipes
for obtaining a random number between [0,1], but I can't make them work.

So, does anyone know how to generate random number x, for 0<= x <=1??

Thanks,

FBM

That's what I got.......

float rndm = (float) (rand() / RAND_MAX);

and I tried also

float rndm = (float) (rand() % 2);

with no success...


--
Remove '.nospam' from e-mail address to reply by e-mail
Nov 15 '05 #11
Gaijinco wrote:
Why is it better:

rand() / (RAND_MAX / N + 1)

than:

srand(time(0));
rand() % N;


Its not. See: http://www.azillionmonkeys.com/qed/random.html

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

Nov 15 '05 #12

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

Similar topics

11
by: Tom McCallum | last post by:
Can any tell me why rand() is such a bad pseudo-random number generator. In all the articles I have read they say that you can predict the outcome of rand() but when I used its output with NIST's...
7
by: Chris Gordon-Smith | last post by:
I have a simulation program that calls the rand() function at various points while it executes. For the user interface that displays statistics etc. while the program runs, I use the Lazarus GUI...
36
by: Ben Justice | last post by:
For a program in c, I need some random numbers for a system were people are placing bets. This is not a commerical project btw. Generally, I tend to rely on things from the standard library,...
36
by: Profetas | last post by:
Hi, I want to generate a random 8 bit number using rand(0 is that possible? to expecifu the base and the lenght? thanks
8
by: Jack | last post by:
When I use rand(), is the RAND_MAX value how long I am guaranteed that the same value will not appear twice? And is this a floating window? For example, if RAND_MAX is 32767, and I make...
4
by: Siam | last post by:
Hi all, I'm writing a shell language in c++ that supports the generation of random numbers, and by its nature, each command must be executed in a new thread. The call to the random function from...
13
by: Spiros Bousbouras | last post by:
The standard says that rand() should return a pseudo-random number but what does pseudorandom mean ? If an implementation of rand() always returned the same number would it be conforming ? What if...
5
by: ds | last post by:
Hi all, rand() is not thread safe, a fact that may not be so bad after all.. However, I face the following problem: a piece of code uses rand() to get a random sequence, but always seeds with...
10
by: Rafael Cunha de Almeida | last post by:
Hi, I've found several sites on google telling me that I shouldn't use rand() % range+1 and I should, instead, use something like: lowest+int(range*rand()/(RAND_MAX + 1.0))
15
by: Rich Fife | last post by:
Quick rand() question: I know you're not supposed to use "rand() % 1024" for instance, because it focuses on the lower bits. However, it seems to me that given that the argument is not a power...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: 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
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...

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.