http://qs321.pair.com?node_id=1168396


in reply to Re^3: Variables are automatically rounded off in perl (humans)
in thread Variables are automatically rounded off in perl

There is not only a single situation to consider. You present a situation where you want to preserve just slightly more precision than is preserved in that situation if you do nothing but the trivial to achieve your aims.

C:\>perl -le "print 'WTF' if 1.00000000000000 != sqrt(3);" WTF

Wow. If you are using '==' or '!=' on computed floating point values, then you've already lost my sympathy.

I'm sorry, but the default, trivial way that a floating point value is displayed should not be optimized for "preserve every single bit of accuracy if you paste it back in and interpret it as a numeric value". It should be and is optimized for presenting the numeric value to humans.

But there are a vast number of values that cannot be assigned if you restrict yourself to 15 decimal digits.

To be clear, you can certainly assign 17 digits. Perl does not ignore beyond the 15th digit when you make an assignment (even when using a numeric literal).

There are no shortage of easy, simple ways to preserve more accuracy if that is what you aim to do. printf and pack are the first two off the top of my head. Determining a sufficient number of digits to request from printf isn't even a difficult proposition.

To me the sane thing is to have print() deliver a value that, when assigned back to a scalar, will result in the same value.

To me, if you are lazily using the default string representation and just expecting 100% fidelity, then you aren't a very good programmer. To support that stance we'd have to make tabs be printed as \t and most sting values to be printed with quotes around them. Producing a representation that can preserve with perfect fidelity is simply not the purpose of print.

During a recent period when the difference between stored accuracy and default displayed accuracy was less, we got tons of complaints because the result of code like:

my $x = 0; for( 1..100 ) { $x += 0.01; # ... } print $x, $/;

was not a nice "0.5" but "0.5000000000000002". Your plan would make it produce "0.50000000000000022".

People just wanting to get a reasonable representation of a rather mundane value are who the behavior of a plain print should be catered to. People who can't stand miscounting one grain of sand on their huge beach are a much better choice for who needs to do a tiny bit of extra work.

- tye