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
John Peacock
March 7, 2001 13:35
Re: [ID 20010305.005] "use integer" doesn't make rand() return integers
Message ID: wrote:
> If there was no point, why was it requested? "No point" is merely
> your opinion, nothing more or less.

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.

> 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 integer
> 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
to suit one person's DWIM.
> Abigail

I quote from 'perldoc integer':

    This tells the compiler to use integer operations from here to the
    of the enclosing BLOCK. On many machines, this doesn't matter a
    deal for most computations, but on those without floating point
    hardware, it can make a big difference.

    Native integer arithmetic (as provided by your C compiler) is used.
    means that Perl's own semantics for arithmetic operations may not be
    preserved. One common source of trouble is the modulus of negative
    numbers, which Perl does one way, but your hardware may do another.

This is _always_ going to mean a low level change that switches which c 
library is used for operations (+,-,/,*), not function calls (sin, tan,
rand).  It doesn't specify that all "numbers" are "integers" but that
Perl will tread them as such when calculating with them.

John Peacock

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