Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Adding really big numbers

by cpaplham (Initiate)
on Feb 23, 2013 at 00:08 UTC ( #1020253=perlquestion: print w/replies, xml ) Need Help??
cpaplham has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to add one hundred 50-digit numbers together. my code is basically:
my $big_number = 37107287533902102798797998220837590246510135740250 + 46376937677490009712648124896970078050417018260538 + ...;
I have tried  use bignum; but this didn't work. Whenever I print the value, I get an empty string. I only need about 15 digits of precision.

Replies are listed 'Best First'.
Re: Adding really big numbers
by frozenwithjoy (Priest) on Feb 23, 2013 at 00:15 UTC
    Which version of Perl are you using? It works just fine for me on 5.16.1. Using bigint, I get values for every integer. Using bignum, I get values for every int and decimal (except for trailing zeroes). Without an extra module, anything over 20 digits defaults to scientific notation with 15 digits of precision.

    Update: Here is some info on largest positive/negative integers that can be nadled by different setups w/o using modules: Re: maximum value of a scalar

      I'm using 5.14. I agree, it's strange.
        Odd. Works fine for me on 5.14.2. What is your operating system?
Re: Adding really big numbers
by salva (Abbot) on Feb 23, 2013 at 09:33 UTC
    If you need to do that application wide, you can compile a custom perl that uses long doubles to represent floating point numbers.

    x86 long doubles have 80 bits and a resolution of 18 digits. Other architectures as SPARC use 128 bits for long doubles.

    Otherwise, you can use Math::LongDouble or Math::MPFR

Re: Adding really big numbers
by Khen1950fx (Canon) on Feb 23, 2013 at 01:58 UTC
    What lib are you using? How are you declaring accuracy and precision? Maybe this'll help:
    #!/usr/bin/perl -l BEGIN { $| = 1; $^W = 1; } use strict; use warnings; use bignum lib => 'FastCalc'; use Memoize; memoize('really_big'); really_big(); sub really_big { bignum->accuracy(15); bignum->precision(15); my $big_number = 3710728753390210279879799822083759024651013574025 +0 + 46376937677490009712648124896970078050417018260538; print $big_number; }
Re: Adding really big numbers
by ambrus (Abbot) on Mar 13, 2013 at 21:34 UTC

    If you only need about 15 digits of precision, you don't need to do anything special. Perl's built in arithmetic will read the numbers as double-precision floats and add them that way, which gives about 15 digits of precision.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1020253]
Front-paged by Arunbear
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2017-05-23 21:22 GMT
Find Nodes?
    Voting Booth?