develooper Front page | perl.perl5.porters | Postings from March 2001

Re: [ID 20010305.005] "use integer" doesn't make rand() return integers

Thread Previous | Thread Next
Bryan C . Warnock
March 7, 2001 14:56
Re: [ID 20010305.005] "use integer" doesn't make rand() return integers
Message ID:
On Wednesday 07 March 2001 16:35, John Peacock wrote:
> Just because a single user expected 'use integer' to overload rand is
> no reason to add it Perl.  Next a user will wonder why sin or tan don't 
> return only integers when 'use integer' is in place.  And soon, some 
> other user will wonder why all function calls (including user defined) 
> are not cast to integers when 'use integer' is in effect.

Ahem.  I sincerely doubt only a single user had these expectations.  Only a 
single user submitted a bug report.  That isn't the same thing.  

> > 
> > I find rand() returning integers nothing stranger than 3.7 + 1.6 
> > equalling 4.
> rand() returns a floating point number from 0 to < 1.  There is but
> a single integer in that range.  It would be faster to code 'sub {0}'
> and leave it at that.
> > 
> > Why would you *want* rand() to return non-integers if you are doing 
> > arithmetic anyway?
> My point exactly!  There is a conceptual failure here, not a limitation
> of Perl.  If a user wishes to have a random integer between 0 and 9
> inclusive, the simple line of code:
> 	int( rand(10) );
> is sufficient.  There is no reason to change the meaning of 'use
> integer'
> to suit one person's DWIM.

Again, one person is a broad assumption.

A quick (and albeit inconclusive) scan of every piece of perl I could get a 
hold of (without undoing my CPAN mirror), about half the uses of 'rand' are 
exactly as you have above - int(rand($num)).

But, and this is a strong but, nearly every use of rand($num) was used as 
int(rand($num)) - in other words, for its integer value.  

The other half of rand uses were as 'rand()' - and that, too, was almost 
exclusively used for its floating point value.

Personally, I agree with John, in that rand shouldn't be overloaded by 'use 
integer'.  (The rationale behind wanting the integers in the first place 
differs, I think.)

And, of course, Abigail doesn't want rand() overloaded, either - just 
rand($num).  But looking at the usage, the question that should be asked is 
why doesn't rand($num) just return an integer regardless of 'use integer'.? 
A floating point value can still be obtained with rand()*$num.  (Unless 
'use integer' *is* in effect.  Which makes it oh-so-confusing....)

Bryan C. Warnock

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About