views:

480

answers:

5

Consider the following:

print 3 ** 333; #Yields 7.6098802313206e+158

My question is simple: How can I disable scientific notation when working with very large numbers? Basically, I'd like to see all the digits dumped to stdout verbatim.

Is this possible?

A: 

Use printf (or sprintf).

printf("%f", 3**333);

http://perldoc.perl.org/functions/sprintf.html

http://perldoc.perl.org/functions/printf.html

edit: this answer is wrong, read the first comment. I will let it here as a bad example :)

Karel Bílek
Thanks, but I think you misunderstood my question. I want to print "3 ** 333" exactly. The conversion to float doesn't achieve that; all you're doing is appending a bunch of zeros.
Of course. My bad.
Karel Bílek
Upvoted back to zero because the question was stated as one of *formatting*, and this does actually answer "how do I force a number to print without the user of scientific notation", even if it doesn't answer the question of exact *computation*.
hobbs
Why leave it here as a bad example? Why let bad answers live to confuse someone else?
brian d foy
+13  A: 

See Math::BigInt

use Math::BigInt;
$x = Math::BigInt->new("3");
print $x ** 333;

Output:

760988023132059809720425867265032780727896356372077865117010037035791631439306199613044145649378522557935351570949952010001833769302566531786879537190794573523
mobrule
Ace. Just what I needed.
+2  A: 

With numbers that large you may have more digits than the precision used to store the numbers. (Seeing a simple runnable example would have resolved this question).

If you really need to see all 150+ digits, you should use the bigint (for integers), bigrat (for rational numbers) and the bignum (for floating point numbers) modules.

David Harris
+2  A: 

If you want to do it for all integers in your program, you can just add:

use bigint;

If you only want to do it for some integers, you can create Math::BigInt objects.

There is also bignum and Math::BigNum if you are working with floats.

brian d foy
+1  A: 

For very small values see the following code:

my $value = 1e-07;                 # = 0.0000001

# GODDDAMNIT

print $value;                      # prints 1e-07, $value is a number
print sprintf("%f", $value);       # prints 0, $value is a number
print sprintf("%.10f", $value);    # prints 0.0000001000, $value is a number
$value = sprintf("%.10f", $value);
print $value                       # prints 1e-07, $value is a number

# /GODDAMNIT

use bignum;
$value = ($value+0)->bstr();
print $value;                      # prints 0.0000001, $value is a string
no bignum;
print $value;                      # prints 0.0000001, $value is a string

# HOORAY, happy elfes dancing around a tree etc.
Frank Straetz