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;誰に何と言われようと、正規表現を愛するようなやりかたを貫きたい。