This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Re: [ID 20010305.005] "use integer" doesn't make rand() return integers
[perl5.git] / lib / integer.pm
CommitLineData
a0d0e21e
LW
1package integer;
2
b75c8c73
MS
3our $VERSION = '1.00';
4
f06db76b
AD
5=head1 NAME
6
34bbe29d 7integer - Perl pragma to use integer arithmetic instead of floating point
f06db76b
AD
8
9=head1 SYNOPSIS
10
11 use integer;
12 $x = 10/3;
13 # $x is now 3, not 3.33333333333333333
14
15=head1 DESCRIPTION
16
34bbe29d
JA
17This tells the compiler to use integer operations from here to the end
18of the enclosing BLOCK. On many machines, this doesn't matter a great
19deal for most computations, but on those without floating point
20hardware, it can make a big difference in performance.
f06db76b 21
34bbe29d
JA
22Note that this only affects how certain operators handle their operands
23and results, and not all numbers everywhere. Specifically, C<use
24integer;> has the effect that before computing the result of X + Y, X -
25Y, X / Y, X * Y, X % Y, or -X (unary minus), the operands X and Y have
26their fractional portions truncated, and the result will have its
27fractional portion truncated as well. For example, this code
a3cb178b
GS
28
29 use integer;
34bbe29d
JA
30 $x = 5.8;
31 $y = 2.5;
32 $, = ", ";
33 print $x, -$x, $x + $y, $x - $y, $x / $y, $x * $y;
34
35will print: 5.8, -5, 7, 3, 2, 10
36
37Note that $x is still printed as having its true non-integer value of
385.8 since it wasn't operated on. Also, arguments passed to functions
39and the values returned by them are not affected by C<use integer;>.
40E.g.,
41
42 srand(1.5);
43 $, = ", ";
44 print sin(.5), cos(.5), atan2(1,2), sqrt(2), rand(10);
45
46will give the same result with or without C<use integer;> The power
47operator C<**> is also not affected, so that 2 ** .5 is always the
48square root of 2.
49
50Finally, C<use integer;> also has an affect on the bitwise operators
51"&", "|", "^", "~", "<<", and ">>". Normally, the operands and results
52are treated as unsigned integers, but with C<use integer;> the operands
53and results are signed. This means, among other things, that ~0 is -1,
54and -2 & -5 is -6.
55
56Internally, native integer arithmetic (as provided by your C compiler)
57is used. This means that Perl's own semantics for arithmetic
58operations may not be preserved. One common source of trouble is the
59modulus of negative numbers, which Perl does one way, but your hardware
60may do another.
61
62 % perl -le 'print (4 % -3)'
63 -2
64 % perl -Minteger -le 'print (4 % -3)'
65 1
47f6b1df 66
f06db76b
AD
67See L<perlmod/Pragmatic Modules>.
68
69=cut
70
d5448623
GS
71$integer::hint_bits = 0x1;
72
a0d0e21e 73sub import {
d5448623 74 $^H |= $integer::hint_bits;
a0d0e21e
LW
75}
76
77sub unimport {
d5448623 78 $^H &= ~$integer::hint_bits;
a0d0e21e
LW
79}
80
811;