Where in the perl documentation does it mention 0.0001, 0.00001 printing differences?
Asked Answered
H

1

6

Where in the perl documentation does it mention when one will get exponential format here?

$ perl -wle 'print for 0.001, 0.0001, 0.00001, 1.00001;'
0.001
0.0001
1e-05
1.00001

No I am not talking about printf today. Where does it say something like "numbers tinier than 0.0001 will get printed differently"?

Heliport answered 18/3, 2023 at 0:37 Comment(2)
Someone voted to close this as "seeking recommendations", btw. Rewording the question as "why are some numbers printed differently" might appease the pedants and overly literal minded.Ordinand
Thanks, but with my luck whatever I do I will only screw it up worse. But thanks anyway!!Heliport
O
10

It's not very clear or easy to find, no. You have to dig into the internals to get anything relevant.

From perlapi:

Gconvert

This preprocessor macro is defined to convert a floating point number to a string without a trailing decimal point. This emulates the behavior of sprintf("%g"), but is sometimes much more efficient. If gconvert() is not available, but gcvt() drops the trailing decimal point, then gcvt() is used. If all else fails, a macro using sprintf("%g") is used.

And perlnumber says that conversions from native floating point to decimal string "involve steps performed by the C compiler", which I assume means the aforementioned Gconvert macro. So you have to look into how those functions behave on your system for the gritty details about when it switches between regular and scientific notation to render a number.

Ordinand answered 18/3, 2023 at 1:36 Comment(2)
It seems one is forced to add massive workarounds if one wants consistent results: perl -wle '$x=.000000001+0; $y=sprintf "%.22f", $x; $y =~ s/0*$//; print $x," : ", $y;'Heliport
@Dan Jacobson, If you want a general solution, that's not it. Always rounding after 22 decimal places is going to cause problems. It's probably too big for some numbers (such as 0.1), and it's way too small for others. Numbers can have way more than 22 decimal places. In fact, the number with the longest decimal form (which is the smallest number IEEE doubles can represent) has 1074 decimal places. And that's not even counting the fact that it leaves a trailing . for integers, and that it doesn't handle +Inf, -Inf and NaN.Cusp

© 2022 - 2024 — McMap. All rights reserved.