Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Integer overflow question

by thospel (Hermit)
on Jan 02, 2005 at 19:02 UTC ( [id://418807]=note: print w/replies, xml ) Need Help??


in reply to Integer overflow question

The answer to this sort of question is not that straightforward. If you use a 32-bit perl, your values start out as an IV (integer value), so you might think the maximum is 2**31-1. If you however add one to that, the value will become an UV (unsigned integer value), and you might think the maxiumum is 2**32-1. However, when you add 1 to that, the value becomes a NV (float value). That one has a very high maximum value, but that one is in fact irrelevant because long before that point you lose resolution and adding 1 will not change the value anymore. That typically happens somewhere around 9e15 (depends on the exact float resolution on your system). Still, this should be way beyond any foreseeable number of transactions unless you do millions of them per second (though if you need a string representation you may have to use (s)printf in order to get all significant digits).

Conclusion: normally you simply don't have to worry about integer overflow of a counter at the perl end.

If you need even more digits (or don't want to bother with (s)printf for big values), simply use an integer in string form and use ++, which will then be magic and have no restriction whatsoever, e.g.:

perl -wle '$a = "9" x 100; $a++; print $a'
will give you 1 folowed by 100 zeros

Replies are listed 'Best First'.
Re^2: Integer overflow question
by bart (Canon) on Jan 03, 2005 at 15:16 UTC
    That typically happens somewhere around 9e15
    The resolution typically is 53 bits, as customary in IEEE floats.
    print 2**53; __END__ 9.00719925474099e+015

    and on my system:

    $\ = "\n"; my $x = 2**53; my $y = 2**53+1; my $z = 2**53-1; print $y-$x; print $x-$z; __END__ 0 1

    So that is indeed the threshold here. (ActivePerl 5.8.4 on Win32)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://418807]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2024-04-20 03:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found