Just another Perl shrine PerlMonks

### Question on simple arithmetic using perl

 on Sep 28, 2011 at 21:27 UTC Need Help??
perlbaski has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I ran below code with use integer line commented and uncommented.

```#!/usr/bin/perl
#use integer;
my \$max_neg_num=((2**32)-1);
print "\nmax neg num is \$max_neg_num\n";
\$error=4294967263 -\$max_neg_num-1;
print "error is \$error \n";

With use integer commented: max neg num is 4294967295 error is -33

With use integer uncommented. max neg num is -2 error is -32

When I looked at integer pragma documentation, it says numbers are wrapped around after largest +ve number i.e. 2^31-1. By that logic max neg number should be -1 represented by 2^32-1.

Also, I am surprised that without integer pragma, how come I am able to see the results correctly even though it is 32 bit machine? I think its a naive question, but I am afraid I will remain naive if I dont ask it. I would like to know how such arithmetic is handled on 32 bit machines. Is there a potability issue if I write the code as above with use integer commented?

Replies are listed 'Best First'.
Re: Question on simple arithmetic using perl
by Anonymous Monk on Sep 28, 2011 at 21:34 UTC

When the number becomes too large for an integer it is automagically promoted to a float.

Thank you Monk!! So does this mean its fine to use such arithmetic and not worry about whether perl can handle it correctly?
No. A float can represent a wider range of values, but a lesser number of significant digits than an integer.

I'm not quite sure what the question is:

```#!/usr/bin/perl -w
use strict;

my \$all_bits_are_on = -1;
printf ("all_bits => %X\n", \$all_bits_are_one);

my \$x = \$all_bits_are_on + 1;
print "Adding -1 to +1 is: \$x\n";

__END__
all_bits => FFFFFFFF
Adding -1 to +1 is: 0
Re: Question on simple arithmetic using perl
by eyepopslikeamosquito (Chancellor) on Sep 29, 2011 at 10:58 UTC

Also, be aware that Perl supports arbitrary size integers via the core Math::BigInt module. For example:

```use Math::BigInt;
my \$x = Math::BigInt->new('123456789012345678901234567890');
my \$y = '123456789012345678901234567890';
\$x += 1;
\$y += 1;
print "x=\$x\n";
print "y=\$y\n";
prints:
```x=123456789012345678901234567891
y=1.23456789012346e+029

Create A New User
Node Status?
node history
Node Type: perlquestion [id://928429]
Approved by ww
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2018-02-23 04:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
When it is dark outside I am happiest to see ...

Results (300 votes). Check out past polls.

Notices?