我正在处理纬度和经度以确定商业地点并遇到一些奇怪的行为。
在下面的Perl代码段中,将数据分配给$v1
的等式计算结果为1.当我调用acos($v1)
时,我收到sqrt
错误。当我拨打acos("$v1")
(带引号)时,我没有。调用acos(1)
也不会产生错误。为什么报价很重要?
use strict;
use warnings 'all';
sub acos {
my $rad = shift;
return (atan2(sqrt(1 - $rad**2), $rad));
}
my $v1 = (0.520371764072297 * 0.520371764072297) +
(0.853939826425894 * 0.853939826425894 * 1);
print acos($v1); # Can't take sqrt of -8.88178e-16 at foo line 8.
print acos("$v1"); # 0
答案 0 :(得分:15)
$v1
不完全是1:
$ perl -e'
$v1 = (0.520371764072297 * 0.520371764072297) +
(0.853939826425894 * 0.853939826425894 * 1);
printf "%.16f\n", $v1
'
1.0000000000000004
但是,当您对其进行字符串化时,Perl only keeps 15 digits of precision:
$ perl -MDevel::Peek -e'
$v1 = (0.520371764072297 * 0.520371764072297) +
(0.853939826425894 * 0.853939826425894 * 1);
Dump "$v1"
'
SV = PV(0x2345090) at 0x235a738
REFCNT = 1
FLAGS = (PADTMP,POK,pPOK)
PV = 0x2353980 "1"\0 # string value is exactly 1
CUR = 1
LEN = 16