Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re: Detecting ineger overflow

by dchetlin (Friar)
on Dec 10, 2000 at 21:46 UTC ( #45953=note: print w/replies, xml ) Need Help??

in reply to Detecting ineger overflow

If you'll only be adding positive numbers and you can guarantee that all parameters passed to add() will be within integer range, a heuristic as simple as this will work:

sub add { use integer; my $result = $_[0] + $_[1]; return $result if $result < $_[0] or $result < $_[1]; goto &myadd; }

That technique can be extended if you need to handle negative overflow as well.

If you can't guarantee the integrity of your parameters, you'll need to know in advance the overflow point of the system you're on. This is something that you could potentially test for in your Makefile.PL. Once you know that, you can test each incoming parameter against the top and bottom, and then add them if they pass.

P.S. A few points about quidity's response above: I believe that due to the nature of arbitrary precision integer math, making these checks beforehand will be a speed win in most cases. Also, Math::BigInt is disgustingly slow; if you want to be embarassed, compare it to Python or Ruby's built-in bigints for speed. There is a Math::BigIntFast on the CPAN -- I haven't benchmarked it yet. You might take a look at that.

Another plus for Python and Ruby is that they automatically upgrade to bigints/bignums, while you have to explicitly load the BigInt library and do it by hand in Perl. This is something I'd very much like to see.

P.P.S. Nick Clark is working on some modifications that will make integer math in Perl be much more sensible (though I haven't yet heard any plans to involve bigints). If you're interested in this sort of thing, take a look here, for instance.


Replies are listed 'Best First'.
(tye)Re2: Detecting ineger overflow
by tye (Sage) on Dec 12, 2000 at 00:10 UTC

    Math::BigInt was an experiment and shouldn't have gotten such a nice name. I think Bit::Vector does much the same things and more much more quickly.

            - tye (but my friends call me "Tye")

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://45953]
NodeReaper patrols the perimeter

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2018-06-19 00:04 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (111 votes). Check out past polls.