「切り捨て」に int() は使うべからず - にぽたん研究所

April 14, 2005

「切り捨て」に int() は使うべからず

Perl で、浮動小数点数の整数化 (小数点以下の切り捨て) をやる場合、 int() を常用していたけど、どうやら、これは基本的に推奨されてないということを、今更ながら知る。

これって常識?
% 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 counterintu-
        itive 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().
ということだそうで、
my $decimal = sprintf("%d", $float);
とか
use POSIX qw(:math_h);
my $decimal = floor($float);
みたいにせんとイカンようだ…。
っていうか、「int() で切り捨てる」というのが浸透しすぎているような気がするのは自分だけだろうか。
今まで何の疑いもなく int() 使ってきた…。

もうさ、ウザいから、これからこれを常識にしようよ。
(my $decimal = $float) =~ s/^([-+]?\d+)(?:\.\d+)?$/$1/ee;
誰に何と言われようと、正規表現を愛するようなやりかたを貫きたい。

nipotan at 21:04 | Comments(2) | TrackBack(1) | tech 
livedoor clipHatena::Bookmarkdel.icio.us

Trackback URL for this entry

Trackbacks

1. perl プログラムの質問です。  [ にぽたん研究所 ]   June 02, 2005 13:33
perl プログラムの質問です。はじめまして perlプログラミング初歩的な質問です。 まず下の例を見てください。 $te = 150000 * 0.0055 $te1 = te * 12 $te3 = 150000 + $te1 $te4 = te3 / 12 ↑このまま計算してしまうと $te4は 13325 となりますが、 ここで質.

Comments

1. Posted by anonymous    April 16, 2005 12:11
BASICを使っていたときから常識でしたが。。。
2. Posted by    April 19, 2005 00:17
そういえば、

use integer;

って人気ないなあ。あまりに人気がないので(苦笑) Perl 5.8 では裏で結構これをやっていたりする。Encodeではこれが以外なところでドーンなきっかけになったっけ。

クイズ:それはどこ?

Post a comment

Name:
URL:
  Remember info?: Rate: Face    Star