Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a different result when I do math on a quoted vs. non-quoted variable?

Tags:

perl

I am working with latitudes and longitudes to determine business locations and ran into some odd behavior.

In the Perl snippet below, the equation assigning data to $v1 evaluates to 1. When I call acos($v1), I receive a sqrt error. When I call acos("$v1") (with quotes), I do not. Calling acos(1) does not produce the error, either. Why do the quotes matter?

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
like image 521
x2m Avatar asked Dec 29 '16 18:12

x2m


People also ask

What do quotations in math mean?

The answer after we divide one number by another. dividend ÷ divisor = quotient. Example: in 12 ÷ 3 = 4, 4 is the quotient.

Do you have to use quotation marks when referencing?

You should use quotation marks any time you use words directly from another source. Sometimes, students think putting a citation or reference at the end “covers it,” but you must use quotation marks to indicate borrowed words.

How do quotation marks work?

The primary function of quotation marks is to set off and represent exact language (either spoken or written) that has come from somebody else. The quotation mark is also used to designate speech acts in fiction and sometimes poetry.

What do quotation marks mean after numbers?

A prime is a symbol similar to an apostrophe or a close quotation mark that in technical usage follows a number to denote a unit; in lay content, a single prime (′) most frequently represents feet or minutes, and a double prime (″) indicates inches or seconds (“The deck is 10′ 6″ by 12′”) or minutes (“The duration was ...


1 Answers

$v1 is not exactly 1:

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

However, when you stringify it, 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
like image 177
ThisSuitIsBlackNot Avatar answered Nov 15 '22 23:11

ThisSuitIsBlackNot