Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To what precision does perl print floating-point numbers?

my $num = log(1_000_000) / log(10);
print "num: $num\n";
print "int(num): " . int($num) . "\n";
print "sprintf(num): " . sprintf("%0.16f", $num) . "\n";

produces:

num: 6
int(num): 5
sprintf(num): 5.9999999999999991

To what precision does perl print floating-point numbers?

Using: v5.8.8 built for x86_64-linux-thread-multi

like image 735
garrett Avatar asked Dec 31 '12 17:12

garrett


People also ask

How much is the precision of floating-point?

The data type float has 24 bits of precision. This is equivalent to only about 7 decimal places. (The rest of the 32 bits are used for the sign and size of the number.) The number of places of precision for float is the same no matter what the size of the number.

Are floating-point numbers precise?

A single-precision, floating-point number is a 32-bit approximation of a real number. The number can be zero or can range from -3.40282347E+38 to -1.17549435E-38, or from 1.17549435E-38 to 3.40282347E+38.

Is 3.0 a floating-point number?

The number 3.0 is the literal representation of a double value (it's equivalent to 3.0d ), whereas 3.0f is a float value. The different precisions explain why you're getting different results - a double is stored using 64-bits, a float uses 32-bits.


1 Answers

When stringifying floating point numbers, whether to print or otherwise, Perl generally uses the value of DBL_DIG or LDBL_DIG from the float.h or limits.h file where it was compiled.

This is typically the precision of the floating point type perl will use rounded down. For instance, if using a typical double type, the precision is 53 bits = 15.95 digits, and Perl will usually stringify with 15 digits of precision.

like image 150
ysth Avatar answered Oct 06 '22 00:10

ysth