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

N groups of random numbers with different ranges

hi,
for a test i want to generate different random numbers between
different ranges in a single loop. I tried to solve in the following
way but it always profile same value. I am looking for suggestion in
this regard.

#include <cstdlib>
#include <time.h>
#include<iostream.h>

int main()
{
int i,j;
for(i=0;i<n;i++) //N set of rendom numbers
{
j=randomize(1,5); // first number
cout<<j;
j=randomize(1,6); // second number and so on..
cout<<j;
}
}

int randomize(int LOW,int HIGH)
{
int value;
time_t seconds;// Declare variable to hold seconds on
//clock.
time(&seconds);//Get value from system clock and place in
//seconds variable.
srand((unsigned int) seconds);//Convert seconds to a
//unsigned integer.
value = rand() % (HIGH - LOW + 1) + LOW;//Get the random
//value between LOW and HIGH
return value;
}

Aug 2 '07 #1
11 1902
Masud <Go**********@gmail.comwrites:
for a test i want to generate different random numbers between
different ranges in a single loop. I tried to solve in the following
way but it always profile same value. I am looking for suggestion in
this regard.

#include <cstdlib>
Make this '#include <stdlib.h>'.
#include <time.h>
#include<iostream.h>
Wrong language; that's C++. Use '#include <stdio.h>'.
int main()
{
int i,j;
for(i=0;i<n;i++) //N set of rendom numbers
There's no declaration of 'n'. This obviously isn't your actual code.
{
j=randomize(1,5); // first number
There's been no declaration of 'randomize' yet. You can probably get
away with this, but you should always declare functions before calling
them. In this case, you could just move the definition of randomize
above the definition of main.
cout<<j;
j=randomize(1,6); // second number and so on..
cout<<j;
}
}

int randomize(int LOW,int HIGH)
{
int value;
time_t seconds;// Declare variable to hold seconds on
//clock.
time(&seconds);//Get value from system clock and place in
//seconds variable.
srand((unsigned int) seconds);//Convert seconds to a
//unsigned integer.
value = rand() % (HIGH - LOW + 1) + LOW;//Get the random
//value between LOW and HIGH
return value;
}
Unless you have a special reason to do otherwise, call srand() just
once at the beginning of your program; then you can call rand()
multiple times. You're probably getting the same result each time
because your program takes less than a second to run, so you get the
same result from time() each time.

The comp.lang.c FAQ is at <http://www.c-faq.com/>. Questions 13.15
through 13.21 deal with random numbers.

--
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."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 2 '07 #2
Masud wrote:
hi,
for a test i want to generate different random numbers between
different ranges in a single loop. I tried to solve in the following
way but it always profile same value. I am looking for suggestion in
this regard.

#include <cstdlib>
#include <time.h>
#include<iostream.h>
One of these headers is a C++ header and not a C header.
The C++ <cstdlibheader corresponds to the C header <stdlib.h>
One of these headers is superficially a C++ header, but isn't, and is
not a C header.
There is no C header corresponding to the C++ header <iostream>.
Notice the name of the C++ header.
One of these headers is a C header, the use of which is deprecated for C++:
The C header <time.hhas a corresponding C++ header <ctime>

These suggest that you want to post to <news:comp.lang.c++and not to
<news:comp.lang.c>. C++ and C are different languages. When you do post
to comp.lang.c++, make your headers
#include <cstdlib>
#include <ctime>
#include <iostream>
Do them the favor, which you did not do for us, of checking earlier
posts and their FAQ. You also need to learn to properly specify the
namespace for standard identifiers, whether explicitly on each use or
which a "using" clause, unless you want to be laughed out of court.

Further, calling srand() in your function randomize is a logical error.
Call srand() once before using rand(). Subsequent calls of srand() are
very unlikely to do what you want.

Do not use the '%' operator to reduce the range of random numbers. It
is a gross error, even with a good pseudo-random number generator. If
you had done comp.lang.c the courtesy of following the newsgroup for
even one day before posting you would know this already, as well as
knowing where to find why it is an error and what to do about it. But,
sure, being rude is a sign of your grandeur as a programmer.
>
int main()
{
int i,j;
for(i=0;i<n;i++) //N set of rendom numbers
{
j=randomize(1,5); // first number
cout<<j;
j=randomize(1,6); // second number and so on..
cout<<j;
}
}

int randomize(int LOW,int HIGH)
{
int value;
time_t seconds;// Declare variable to hold seconds on
//clock.
time(&seconds);//Get value from system clock and place in
//seconds variable.
srand((unsigned int) seconds);//Convert seconds to a
//unsigned integer.
value = rand() % (HIGH - LOW + 1) + LOW;//Get the random
//value between LOW and HIGH
return value;
}
Aug 2 '07 #3
On Thu, 02 Aug 2007 02:03:44 -0700, Masud wrote:
hi,
for a test i want to generate different random numbers between
different ranges in a single loop. I tried to solve in the following
way but it always profile same value. I am looking for suggestion in
this regard.

#include <cstdlib>
This is a C++ header. In C it is called <stdlib.h>
#include <time.h>
#include<iostream.h>
There is no such header in C. For C++, go to comp.lang.c++.
For C, use <stdio.h>
(anyway, the answer to your question is the same in both
languages, so I will answer here)
int main()
{
int i,j;
for(i=0;i<n;i++) //N set of rendom numbers
{
j=randomize(1,5); // first number
cout<<j;
In C, use printf("%d", j)
j=randomize(1,6); // second number and so on..
cout<<j;
Sure you don't want any whitespace?
}
}

int randomize(int LOW,int HIGH)
Traditionally, UPPERCASE names are used for preprocessor macros.
The compiler doesn't care, but the reader (including yourself) can
find it helpful to determine whether something is a macro at a
glance.
{
int value;
time_t seconds;// Declare variable to hold seconds on
//clock.
time(&seconds);//Get value from system clock and place in
//seconds variable.
srand((unsigned int) seconds);//Convert seconds to a
//unsigned integer.
<OTYou included <cstdlib>, not <stdlib.h>, so you must use
std::srand (or include a using std::srand; or using namespace std;
somewhere). </OT>
value = rand() % (HIGH - LOW + 1) + LOW;//Get the random
//value between LOW and HIGH
See www.c-faq.com, question 13.15 onwards. In theory, this is
correct (provided HIGH - LOW + 1 is much less than RAND_MAX,
otherwise it is biased), but with many implementations of rand()
it is very poor.
return value;
}
--
Army1987 (Replace "NOSPAM" with "email")
"Never attribute to malice that which can be adequately explained
by stupidity." -- R. J. Hanlon (?)

Aug 2 '07 #4
On Thu, 02 Aug 2007 06:06:58 -0400, Martin Ambuhl wrote:
Masud wrote:
[...]
>#include <cstdlib>
#include <time.h>
#include<iostream.h>
[...]
There is no C header corresponding to the C++ header <iostream>.
Notice the name of the C++ header.
<otIIRC, <iostream.his a deprecated C++ header which also
declares identifiers in the unnamed namespace (e.g. cout as well
as std::cout, etc.). </ot>
--
Army1987 (Replace "NOSPAM" with "email")
"Never attribute to malice that which can be adequately explained
by stupidity." -- R. J. Hanlon (?)

Aug 2 '07 #5
Martin Ambuhl <ma*****@earthlink.netwrites:
[...]
Do not use the '%' operator to reduce the range of random numbers. It
is a gross error, even with a good pseudo-random number generator.
[...]

Is that true? It seems to me that with a sufficiently good PRNG,
using the '%' operator should yield good results (ignoring the bias
introduced if the range is not a factor of RAND_MAX+1). Using '%' is
a bad idea because the lower bits provided by some PRNGs are poor.

--
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."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 2 '07 #6
Army1987 wrote:
On Thu, 02 Aug 2007 06:06:58 -0400, Martin Ambuhl wrote:
Masud wrote:
[...]
#include <cstdlib>
#include <time.h>
#include<iostream.h>
[...]
There is no C header corresponding to the C++ header <iostream>.
Notice the name of the C++ header.
<otIIRC, <iostream.his a deprecated C++ header which also
declares identifiers in the unnamed namespace (e.g. cout as well
as std::cout, etc.). </ot>
No, it is not. A deprecated header (or anything else) is one that is
standard but discouraged from use. <iostream.his not a standard
header in C++ at all.


Brian
Aug 2 '07 #7
Default User wrote:
Army1987 wrote:
>On Thu, 02 Aug 2007 06:06:58 -0400, Martin Ambuhl wrote:
>>Masud wrote:
[...]
>>>#include <cstdlib>
#include <time.h>
#include<iostream.h>
[...]
>> There is no C header corresponding to the C++ header <iostream>.
Notice the name of the C++ header.

<otIIRC, <iostream.his a deprecated C++ header which also
declares identifiers in the unnamed namespace (e.g. cout as well
as std::cout, etc.). </ot>

No, it is not. A deprecated header (or anything else) is one that is
standard but discouraged from use. <iostream.his not a standard
header in C++ at all.
And it certainly is not known in C.

--
"Vista is finally secure from hacking. No one is going to 'hack'
the product activation and try and steal the o/s. Anyone smart
enough to do so is also smart enough not to want to bother."

--
Posted via a free Usenet account from http://www.teranews.com

Aug 2 '07 #8
CBFalconer wrote:
Default User wrote:
Army1987 wrote:
<otIIRC, <iostream.his a deprecated C++ header which also
declares identifiers in the unnamed namespace (e.g. cout as well
as std::cout, etc.). </ot>
No, it is not. A deprecated header (or anything else) is one that is
standard but discouraged from use. <iostream.his not a standard
header in C++ at all.

And it certainly is not known in C.

No question about that.


Brian
Aug 2 '07 #9
On Thu, 02 Aug 2007 09:27:01 -0700, Keith Thompson wrote:
Martin Ambuhl <ma*****@earthlink.netwrites:
[...]
>Do not use the '%' operator to reduce the range of random numbers. It
is a gross error, even with a good pseudo-random number generator.
[...]

Is that true? It seems to me that with a sufficiently good PRNG,
using the '%' operator should yield good results (ignoring the bias
introduced if the range is not a factor of RAND_MAX+1). Using '%' is
a bad idea because the lower bits provided by some PRNGs are poor.
I piped a program writing various sizes, up to 256 MB, of the
lowest byte of rand() (i.e.
for (i=0; i < size; i++)
putchar(rand() & 0xFF);
) into ent (http://www.fourmilab.ch/random/), and it didn't find
anything particular (i.e. most times I got that "Chi-squared would
randomly exceed this xx% of times" with xx between 25 and 75; also
the serial correlation coefficient was very close to zero).
(I didn't try that on Windows, I'll try when I have some spare
time.)
--
Army1987 (Replace "NOSPAM" with "email")
"Never attribute to malice that which can be adequately explained
by stupidity." -- R. J. Hanlon (?)

Aug 2 '07 #10
Keith Thompson wrote:
Martin Ambuhl <ma*****@earthlink.netwrites:
[...]
>Do not use the '%' operator to reduce the range of random numbers. It
is a gross error, even with a good pseudo-random number generator.
[...]

Is that true? It seems to me that with a sufficiently good PRNG,
using the '%' operator should yield good results (ignoring the bias
introduced if the range is not a factor of RAND_MAX+1). Using '%' is
a bad idea because the lower bits provided by some PRNGs are poor.
Why should I ignore the introduction of bias? Simply to declare that
what is a bad idea when I recognize why it is a bad idea is not one when
I ignore that reason?

What other things do you ignore the bad features of? Ignoring the
possible results of a gunshot wound it is not a bad idea to shoot
yourself in the head.

Aug 2 '07 #11
On Thu, 02 Aug 2007 21:04:00 +0200, Army1987 wrote:
On Thu, 02 Aug 2007 09:27:01 -0700, Keith Thompson wrote:
>Martin Ambuhl <ma*****@earthlink.netwrites:
[...]
>>Do not use the '%' operator to reduce the range of random numbers. It
is a gross error, even with a good pseudo-random number generator.
[...]

Is that true? It seems to me that with a sufficiently good PRNG,
using the '%' operator should yield good results (ignoring the bias
introduced if the range is not a factor of RAND_MAX+1). Using '%' is
a bad idea because the lower bits provided by some PRNGs are poor.

I piped a program writing various sizes, up to 256 MB, of the
lowest byte of rand() (i.e.
for (i=0; i < size; i++)
putchar(rand() & 0xFF);
) into ent (http://www.fourmilab.ch/random/), and it didn't find
anything particular (i.e. most times I got that "Chi-squared would
randomly exceed this xx% of times" with xx between 25 and 75; also
the serial correlation coefficient was very close to zero).
(I didn't try that on Windows, I'll try when I have some spare
time.)
With Microsoft Visual Studio 2005 Express:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define SIZE /* see below */
int main(void)
{
size_t n = SIZE;
FILE *out = fopen("rnd.dat", "wb");
if (out == NULL) { perror("fopen"); exit(EXIT_FAILURE); }
srand(time(NULL));
while (n--)
putc(rand() & 0xFF, out); /* CHAR_BIT == 8 */
if (fclose(out) != 0) { perror("fclose"); exit(EXIT_FAILURE); }
return 0;
}

Test: SIZE: Chi square: Serial corr. coefficient:
1 256 264.00 (50%) 0.016030
2 256 286.00 (10%) -0.009120
3 256 260.00 (50%) -0.215230
4 64KB 242.59 (50%) 0.001587
5 64KB 246.53 (50%) -0.003934
6 64KB 231.28 (75%) -0.005520
7 16MB 0.00 (99.99%) 0.000011
(All the values occurred exactly 65536 times; other two tests with
this SIZE gave identical results, except for the Monte Carlo value
for Pi.)

With Microsoft Visual Studio 2005 Express: #include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define SIZE 256
int main(void)
{
size_t n = SIZE;
FILE *out = fopen("rnd.dat", "wb");
if (out == NULL) { perror("fopen"); exit(EXIT_FAILURE); }
srand(time(NULL));
while (n--)
putc(rand() >7, out); /* CHAR_BIT == 8, RAND_MAX = 0x7fff */
if (fclose(out) != 0) { perror("fclose"); exit(EXIT_FAILURE); }
return 0;
}

Test: SIZE: Chi square: Serial corr. coefficient:
1 256 266.00 (50%) -0.104760
2 256 260.00 (50%) -0.017179
3 256 280.00 (25%) -0.007335
4 64KB 249.76 (50%) -0.003254
5 64KB 251.86 (50%) -0.002133
6 64KB 242.18 (50%) 0.001661
7 16MB 257.22 (50%) 0.000057
8 16MB 255.54 (50%) -0.000184
9 16MB 253.16 (50%) -0.000410

I haven't saved the results anywhere, but with Ubuntu 6.10,
gcc version 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5),
libc6 version 2.4-1ubuntu12, I recall that there were no obvious
differences between rand() & 0xFF and rand >15 (RAND_MAX is
2147483647 here).
--
Army1987 (Replace "NOSPAM" with "email")
"Never attribute to malice that which can be adequately explained
by stupidity." -- R. J. Hanlon (?)

Aug 3 '07 #12

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

Similar topics

15
by: Roman Töngi | last post by:
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; ...
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...
13
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...
15
by: Papajo | last post by:
Hi, This script will write a random number into a document write tag, I've been trying to get it to write into a input form box outside the javascript, any help is appreciated. Thanks Joe ...
12
by: Adam Hartshorne | last post by:
Hi All, I was wondering if somebody could post a few lines of code which would produce random colors, which will be used in defining different regions on a mesh. So in addition to having n...
104
by: fieldfallow | last post by:
Hello all, Is there a function in the standard C library which returns a prime number which is also pseudo-random? Assuming there isn't, as it appears from the docs that I have, is there a...
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,...
7
by: Koppe74 | last post by:
Sorry for this newbee question, but here goes... I of course knows about the rand()-function, but are there any functions that yields an integer randomnumber between 0 (or 1) and a *programmer...
3
by: WP | last post by:
Hello, I'm having some problems with the TR1 random number generators. I need a function that takes a min and max value and generates a random number within that range (inclusive). Here's my...
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
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
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
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...

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.