为什么Perl的sprintf不能正确地舍入浮点数? [英] Why does Perl's sprintf not round floating point numbers correctly?

查看:204
本文介绍了为什么Perl的sprintf不能正确地舍入浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找Perl内置函数 sprintf



我以为它做了一个正常的四舍五入(例如ROUND_HALF_UP,如 Java的四舍五入模式约定),但挖掘进一步证明这是错误的:

 > /usr/local/bin/perl5.10.1 -e'print(sprintf(%。2f,shift @ARGV)。\\\
);'0.335
0.34
> /usr/local/bin/perl5.10.1 -e'print(sprintf(%。2f,shift @ARGV)。\\\
);'1.335
1.33
$ div $解析方案

你已经被浮动数字不是十进制小数的精确表示的事实所咬。这是我得到的:

  DB< 1> $ a = 0.335 

DB< 5>打印sprintf(%。19f,$ a)
0.3350000000000000200
DB< 7> $ b = 1.335

DB< 8>打印sprintf(%。19f,$ b)
1.3349999999999999645
DB< 9>




$ b由于0.335在内部表示为略大于0.335,所以转换为0.34,而1.335略低于LESS超过1.335,所以涨到了1.33。


I was out looking for the rounding convention used by Perl's built-in function sprintf.

I was thinking that it does a normal rounding (e.g. ROUND_HALF_UP as in Java's rounding mode convention), but digging further proved this to be wrong:

> /usr/local/bin/perl5.10.1 -e 'print(sprintf("%.2f", shift @ARGV)."\n");' 0.335
0.34
> /usr/local/bin/perl5.10.1 -e 'print(sprintf("%.2f", shift @ARGV)."\n");' 1.335
1.33

解决方案

You have been bitten by the fact that floating point numbers are not exact representations of decimal fractions. Here's what I get:

  DB<1> $a=0.335

  DB<5> print sprintf("%.19f",$a)
0.3350000000000000200
  DB<7> $b=1.335

  DB<8> print sprintf("%.19f",$b)
1.3349999999999999645
  DB<9> 

Since 0.335 is represented internally as slightly larger than 0.335 it rounds to .34, while 1.335 is slightly LESS than 1.335, so it rounds to 1.33.

这篇关于为什么Perl的sprintf不能正确地舍入浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆