delorie.com/archives/browse.cgi   search  
Mail Archives: cygwin/2001/04/30/16:14:39

Mailing-List: contact cygwin-help AT sourceware DOT cygnus DOT com; run by ezmlm
List-Subscribe: <mailto:cygwin-subscribe AT sources DOT redhat DOT com>
List-Archive: <http://sources.redhat.com/ml/cygwin/>
List-Post: <mailto:cygwin AT sources DOT redhat DOT com>
List-Help: <mailto:cygwin-help AT sources DOT redhat DOT com>, <http://sources.redhat.com/ml/#faqs>
Sender: cygwin-owner AT sources DOT redhat DOT com
Delivered-To: mailing list cygwin AT sources DOT redhat DOT com
Date: Mon, 30 Apr 2001 15:42:02 -0400
From: Charles Krug <charles AT pentek DOT com>
To: cygwin AT cygwin DOT com
Subject: Re: Random Number Generator--program bug
Message-ID: <20010430154202.C13085@pentek.com>
References: <32 DOT 143dcec3 DOT 281efce6 AT aol DOT com> <4 DOT 3 DOT 1 DOT 2 DOT 20010430141203 DOT 01659b48 AT pop DOT ma DOT ultranet DOT com>
Mime-Version: 1.0
User-Agent: Mutt/1.2.5i
In-Reply-To: <4.3.1.2.20010430141203.01659b48@pop.ma.ultranet.com>; from lhall@rfk.com on Mon, Apr 30, 2001 at 02:13:08PM -0400

On Mon, Apr 30, 2001 at 02:13:08PM -0400, Larry Hall (RFK Partners, Inc) wrote:
> At 01:37 PM 4/30/2001, you wrote:

> >void main()

At the risk of being accused of pendantry, main() should be declared as
int.

> >{
> >   int input1, i;
> >
> >   srand(time(NULL));
> >   
> >   for (i=0; i<20 ; i++)
> >     {
> >       input1 = rand() * 10 / (RAND_MAX + 1);

Here's your problem.  You're doing integer math.  10/(RAND_MAX + 1) is
going to be 0.  Think about why . . you're dividing a small integer by a
rather large integer.

Moreover, RAND_MAX is usually an alias for INT_MAX.  Therefore RAND_MAX
+ 1 is an overflow condition.  

Moreover, you don't want the +1 in the denominator.  You want rand()'s
proportion of RAND_MAX--which (should be) a uniform deviate, multiplied
by 10, to bring its range into 0 < 9, and THEN add 1, which will (after
truncation) give you numbers between 1 and 10.

I think what you really want is something like this:

          input1 = (double)rand() * 10.0/((double)RAND_MAX) + 1.0;


> >       printf("random numbers %i\n",input1);
> >
> >     }
> >} 
> Try the latest snapshot at www.cygwin.com.

The OP`s problem was semantic.  He was specifying integer math, but
expecting results of double math.  According to integer math, his result
is correct . . though not what he intended.


Charles

-- 
Charles Krug, Jr.
Applications Engineer
Pentek Corp
1 Park Way
Upper Saddle River, NJ 07458


--
Want to unsubscribe from this list?
Check out: http://cygwin.com/ml/#unsubscribe-simple

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019