I'm prototyping some code that I'll eventually port over to C for an Arduino project I've been working on (much quicker to prototype in Perl first) and am hoping for some feedback from the mathematicians.

So the code is designed to calculate a direction in compass degrees between two sets of GPS coordinates, then convert that degree into a compass direction. The following example is between Calgary, AB, Canada to Toronto, ON, Canada. From what I've found on the Internet, this direction is approximately 94 degrees, which the code outputs correctly.

I completely comprehend and had no problem at all writing the direction() function, but had to do a lot of reading and guessing with the trig stuff in bearing() as it's much beyond my mathematical understanding, and am wondering if it appears reasonably sane.

use warnings; use strict; use Math::Trig; use constant PI => 3.14159265358979; # calgary my $lat1 = 51.32055555555556; my $lon1 = -114.7297222222222221; # toronto my $lat2 = 43.65321111111111; my $lon2 = -79.38321111111111; my $bearing = bearing($lat1, $lon1, $lat2, $lon2); my $direction = direction($bearing); print "$bearing, $direction\n"; sub bearing { my ($lat1, $lon1, $lat2, $lon2) = map { ($_ * PI) / 180 } @_; my $d_lon = $lon2 - $lon1; my $y = sin($d_lon) * cos($lat2); my $x = cos($lat1) * sin($lat2) - sin($lat1) * cos($lat2) * cos($d_lon); my $rad = atan2($y, $x); my $deg = $rad * (180 / PI); return $deg < 0 ? $deg += 360 : $deg; } sub direction { my ($deg) = @_; my @directions = qw( N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW N ); my $calc = (($deg % 360) / 22.5) + .5; return $directions[$calc]; } __END__ 94.0048844699519, E

In reply to Calculate bearing between GPS coordinates by stevieb

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.