2

我在一个文件中有几个不同格式的数字:8.3、0.001、9e-18。我正在寻找一种简单的方法来读取和存储它们而不会损失任何精度。这在 AWK 中很容易,但在 Perl 中是如何完成的呢?我只愿意使用 Perl。谢谢!

另外,我想知道是否有一种简单的方法可以以适当的格式打印它们。例如,8.3 应该打印为“8.3”而不是“8.3e0”

4

2 回答 2

4

如果它们是文本字符串,那么将它们作为字符串读入 Perl 并将它们作为字符串写回不应导致任何精度损失。如果您必须对它们进行算术运算,那么我建议安装 CPAN 模块 Math::BigFloat 以确保您不会因舍入而失去任何精度。

至于你的第二个问题,Perl 不会进行任何重新格式化,除非你要求它:

$ perl -le 'print 8.3'
8.3

我错过了什么吗?

于 2012-04-23T01:31:57.823 回答
1

http://perldoc.perl.org/perlnumber.html

Perl 可以在内部以 3 种不同的方式表示数字:原生整数、原生浮点数和十进制字符串。十进制字符串可能有指数符号部分,如 "12.34e-56" 。这里的 Native 表示“用于构建 perl 的 C 编译器支持的格式”。

这意味着打印数字取决于数字在 perl 内部的存储方式,这反过来意味着您必须知道数字在输入中的表示方式。

总的来说,Perl 只会做正确的事,但您应该知道如何使用编译器,它如何在内部表示数字,以及如何打印这些数字。例如:

 $ perldoc -f int

 int EXPR

      int  Returns the integer portion of EXPR.  If EXPR is omitted, uses $_.  You should
      not use this function for rounding: one because it truncates towards 0, and two
      because machine representations of floating-point numbers can sometimes produce
      counterintuitive results.  For example, "int(-6.725/0.025)" produces -268 rather than
      the correct -269; that's because it's really more like -268.99999999999994315658
      instead.  Usually, the "sprintf", "printf", or the "POSIX::floor" and
      "POSIX::ceil" functions will serve you better than will int().

我认为,如果您想以字符串的形式显式读取数字,最好的办法是使用具有“A*”格式的 unpack()。

于 2012-04-23T03:28:26.400 回答