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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.