Why do I get a different result when I do the math in a quoted or non-quoted variable?

I work with latitudes and longitudes to determine places of work and to encounter some kind of strange behavior.

In the Perl snippet below, the equation assigning the data to $v1 is 1. When I call acos($v1) , I get sqrt error. When I call acos("$v1") (with quotes), I do not. Calling acos(1) also does not raise an error. Why are quotes important?

 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 
+8
perl
source share
1 answer

$v1 not exactly 1:

 $ perl -e' $v1 = (0.520371764072297 * 0.520371764072297) + (0.853939826425894 * 0.853939826425894 * 1); printf "%.16f\n", $v1 ' 1.0000000000000004 

However, when you gate it, Perl only stores 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 
+15
source share

All Articles