Re: Detecting ineger overflowby dchetlin (Friar)
|on Dec 10, 2000 at 21:46 UTC||Need Help??|
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:
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.