473,799 Members | 2,903 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 80604
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******@veriz on.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.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 15 '05 #3

"Fernando Barsoba" <fb******@veriz on.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.goo glegroups.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_RA ND_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******@veriz on.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_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.
Nov 15 '05 #10

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

Similar topics

11
4225
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 random number testsuite it passed all of the tests thrown at it for randomness. Can anyone suggest a test I could use that it would fail? A pointer to a suitable article would be appreciated. Thanks for your help in advance, Tom
7
3249
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 library, which is based on GTK. Depending on which libraries I link in, I can have either a GTK1 or GTK2 user interface. I'm finding that the simulation behaves differently depending on whether I link with GTK1 or GTK2.
36
7140
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, because they're written by people with skills far above mine. Hence, I've always used rand() and FALSELY assumed it could produce unpredictable random numbers and could be used in many situations even if security was an issue. Firstly, lets assume...
36
2696
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
4395
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 500,000 consecutive rand calls then is the rand() algorithm going to guarantee me that no floating window of calls over that 500,000 rand calls will have the same value twice? The only way that would work is if the series was identical everytime.
4
2798
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 my language simply propogates up to the rand( ) function from c++. For some reason, C++ will give each thread independent use of their own rand( ) function, so that a rand( ) call from one thread won't affect another thread's call to rand( )....
13
3672
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 it always alternated between 2 values ? On the practical side do you have any thoughts on what one could realistically expect from the behaviour of rand() ? Could for example one expect that eventually any value in the range will be returned ?
5
2325
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 the same seed for reproducibility of the results. Now I am porting this (old C89) code and have setup a nice app with threads that drives on one thread the old code and on another the new code, so that I can compare the results and see that nothing...
10
3022
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
3948
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 of two (or near a power of two), that this is not an issue. The upper bits will participate equally in the result with the lower. Am I missing something? Thanks!
0
9686
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
9540
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
10475
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
10250
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...
0
9068
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7564
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
6805
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
5463
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...
3
2938
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.