Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

How do I store very large numbers in a PERL variable (i.e., several thousands of digits?). There seems to be some upper limit of about 300 digits, which I am in an urgent need to sidestep. Thanks, Henrik (wonderpop2000@hotmail.comNOSPAM)

Replies are listed 'Best First'.
Re: LARGE numbers in PERL?
by Juerd (Abbot) on Jul 19, 2002 at 06:43 UTC
Re: LARGE numbers in PERL?
by theorbtwo (Prior) on Jul 19, 2002 at 06:56 UTC

    BTW, you should relize that though the floats on your system can represent up to 10**300 (say), they still only have a strongly limited number of significant digits -- not all of the digits actualy get traced. So 10**5+1 == 10**5.

    Also, consider if you want to use Math::BigInt, or rearange your arithmetic to produce smaller numbers. If you don't need all the accuracy, scaling things will make your program much faster. If you do need the accuracy, BigInt and suchlike can be a lifesaver.


    Confession: It does an Immortal Body good.

Re: LARGE numbers in PERL?
by DamnDirtyApe (Curate) on Jul 19, 2002 at 06:50 UTC

    Have you looked at Math::BigInt and Math::BigFloat? I don't know if there's a limit to the size of number they can store, but a quick scan of the docs didn't show one.


    _______________
    D a m n D i r t y A p e
    Home Node | Email
Re: LARGE numbers in PERL?
by Joost (Canon) on Jul 19, 2002 at 11:12 UTC
    There seems to be some upper limit of about 300 digits

    Actually, the limit is a lot smaller: as perl uses floating points to store its numbers, what you end up with is a big inaccurate number. the exact limits and accuracy are dependand.

    If you want to know how perl stores numbers type:

    perl -V
    To see the flags your perl interpreter was compiled with.

    Find the line saying nvtype=' ... ' which is your system representation for perl numbers (usually double I guess). Also uselongdouble and uselongfloat if set to define might make your numbers more accurate.

    You will have to decide for yourself if you care about the inaccuracies, if you do, see Math::Bigint and Math::Bigfloat as mentioned in the posts above.

    Note: If you have a number stored in a string, it will only get converted when use them as numbers. So things like $big_number = '10231273879128749879857'; stay exact if you do not do arithmetics on them (and don't do things like $big_number == $other_number, use $big_number eq $other_number if you really need to).

    -- Joost downtime n. The period during which a system is error-free and immune from user input.