473,796 Members | 2,536 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem of random number generate..

Dear All:
I have a question about this below function.The purpose of this
function is to generate one number between a and b.
--------------------------
int gennum(int a, int b)
{
srand(time(NULL ));
int range = b-a+1;
int x = (rand())%range; <-- problem occur here
int result = a+x;
return result;
}
----------------
this problem pass compile. However it has floating exception when
execution.
I don't know how to solve this problem. Please help me.
Thanks a lot!

Aug 9 '05 #1
6 1778
Sen-Lung Chen wrote:
I have a question about this below function.The purpose of this
function is to generate one number between a and b.
--------------------------
int gennum(int a, int b)
{
srand(time(NULL ));
int range = b-a+1;
int x = (rand())%range; <-- problem occur here
int result = a+x;
return result;
}
----------------
this problem pass compile. However it has floating exception when
execution.
I don't know how to solve this problem. Please help me.
Thanks a lot!


I don't know how a floating point exception can occur when no floating
point type is present in the expression, so I can't help you with this
particular problem; however, the C FAQ has the suggested implementation
for generating random numbers from an interval. Your implementation is
not good since it uses %. Read the C FAQ at
http://www.eskimo.com/~scs/C-faq/top.html, the section 13 is the one of
interest for you.

V
Aug 9 '05 #2
Sen-Lung Chen wrote:
int range = b-a+1; this problem pass compile. However it has floating exception when
execution.
I don't know how to solve this problem. Please help me.
Thanks a lot!


I'd print out rnage. I got the strange feeling from the
behavior it is not a positive number.
Aug 9 '05 #3
Thanks a lot~~
I found the bug. I propagate 0 to range.
It's error.

Thanks for Ron and Victor.

Aug 9 '05 #4
Thanks a lot~~
I found the bug. I propagate 0 to range.
It's error.

Thanks for Ron and Victor.

Aug 9 '05 #5
Sen-Lung Chen wrote:
Dear All:
I have a question about this below function.The purpose of this
function is to generate one number between a and b.
--------------------------
int gennum(int a, int b)
{
srand(time(NULL ));
int range = b-a+1;
int x = (rand())%range; <-- problem occur here
int result = a+x;
return result;
}
----------------
this problem pass compile. However it has floating exception when
execution.
I don't know how to solve this problem. Please help me.
Thanks a lot!


As others have pointed out:
(a) range might be negative.
(b) it might not be a good idea to use % for generating random
integers within a given interval since
(1) depending on RAND_MAX and range the numbers might not
be evenly distributed, and
(2) depending on the implementation of rand(), lower order
bits might not be random.

I would like to add that it is not a good idea to call srand()
within each call to gennum(). Depending on the frequence of calls,
you might get results that would not look random at all. E.g., on
my machine the program

#include <iostream>
#include <cstdlib>

using namespace std;

int gennum(int a, int b)
{
srand(time(NULL ));
int range = b-a+1;
int x = (rand())%range;
int result = a+x;
return result;
}
int main ( void ) {

for ( unsigned int i=0; i<10; ++i ) {
std::cout << gennum(0,10) <<'\n';
}

}

produced:

news_group> a.out
6
6
6
6
6
6
6
6
6
6
Even if time(NULL) actually changes from call to call, you are giving
up all the theory that went into the design of rand(). Thus, you cannot
be sure that your results will pass any test for pseudo-randomness.
Best

Kai-Uwe Bux
Aug 9 '05 #6

"Sen-Lung Chen" <sl****@larc.ee .nthu.edu.tw> wrote in message
news:11******** *************@g 14g2000cwa.goog legroups.com...
Dear All:
I have a question about this below function.The purpose of this
function is to generate one number between a and b.
--------------------------
int gennum(int a, int b)
{
srand(time(NULL ));
Should be:

srand((unsigned int)time(NULL)) ;

Also note that 'srand()' should only be called once, near the start of
program execution. Don't call it before each call to 'rand()'.
int range = b-a+1;
int x = (rand())%range; <-- problem occur here
int result = a+x;
return result;
}
----------------
this problem pass compile. However it has floating exception when
execution.
I don't know how to solve this problem. Please help me.
Thanks a lot!


http://www.eskimo.com/~scs/C-faq/top.html
See sections 13.15 - 13.20
(This is the C FAQ, but this issue also applies to C++.)

Since your example code has no floating point operations, your
'floating exception' must be caused by something else in your
program. Try to create a small, compilable example program
that reproduces the problem and post that. (A benefit of this
approach is that often while doing this, you'll discover the
problem yourself.)

-Mike
Aug 9 '05 #7

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

Similar topics

2
2145
by: vikas | last post by:
hi, I want to generate random numbers in c++ (using vc++ 6.0) on hit of enter. I am using _kbhit(), but don't know how to reset it, so that I can use it again, can anybody help me with this. code is say like following. #include <iostream> #include <conio.h> #include <windows.h>
10
5990
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 System.Random iRnd = new System.Random(); string theNum = iRnd.Next(0,8).ToString(); lblAnswer.Text = iRnd.Next(0,8).ToString();
2
18026
by: Henry | last post by:
Hi, How can I generate an eight digit random? Can I use the staff name to generate it? May I ask is there any sample c# code to see? Thanks
2
1785
by: jerryau | last post by:
Hi, I'm creating a number generator program, that is supposed to generate 6 unique random numbers for each game. I want to generate this for 6 games. The problem is, that it works for the first game, but then all the other games have exactly the same numbers (e.g. Game 1: 1,2,3,4,5,6.. Game 2: 1,2.3,4,5,6). I don't know how to get delete the previous array with those numbers, and then generate a new one. Here is my code:
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...
10
1659
by: Curt_C [MVP] | last post by:
If I use it in my page it's fine but when I put it in a Class file for calling it returns the same # for each call. Any ideas why? I'm sure it's something I'll slap myself for but the only samples I can find are for calling the Random() within the page, not a seperate class. --Page-- myClass myclass = new myClass(); for(int i = 1;i <= 100; i++) {
7
2560
by: Fernando Barsoba | last post by:
Hi, After following the advice received in this list, I have isolated the memory leak problem I am having. I am also using MEMWATCH and I think it is working properly. The program does some calculations and stores elements in a list. After that, a sorting algorithm is used over that list. Two functions are called before the sorting process:
20
7861
by: jjmillertime | last post by:
I'm new so i apologize if this is in the wrong spot. I'm also new to programming in C and i've been searching for quite a while on how to create a program using C that will generate two random numbers, multiply them, and ask you for the result. It also needs to have four responses for both right and wrong answers and should print them randomly as well. The program should use at least 2 functions. Any help would be greatly appreciated. ...
2
1716
by: ccarter45 | last post by:
I guess I really don't have a good understanding of methods, it's really confusing for me. I'm not asking anyone to solve this for me, but any help would be GREATLY appreciated. This is the assignment: Method getIntBetween that gets user input for an integer within certain range. It receives a string, message, to be printed out as the prompt message, and two integer min and max that indicate the desired range of the input. It error-checks the...
26
7921
by: bilgekhan | last post by:
What is the correct method for generating 2 independent random numbers? They will be compared whether they are equal. What about this method: srand(time(0)); int r1 = rand(); srand(rand()); int r2 = rand(); bool f = r1 == r2;
0
9528
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
10230
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...
1
10174
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,...
0
9052
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
7548
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
6788
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
5575
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2926
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.