Angle difference between two bearings: Difference between revisions
Content added Content deleted
(→{{header|Fortran}}: Ah, vector analysis...) |
(Go solution) |
||
Line 186: | Line 186: | ||
1174.8381( 0.996437,-0.084339) -154146.6649(-0.918252, 0.395996) -161.510 |
1174.8381( 0.996437,-0.084339) -154146.6649(-0.918252, 0.395996) -161.510 |
||
60175.7731( 0.826820, 0.562467) 42213.0719( 0.998565,-0.053561) 37.297 |
60175.7731( 0.826820, 0.562467) 42213.0719( 0.998565,-0.053561) 37.297 |
||
</pre> |
|||
=={{header|Go}}== |
|||
'''Basic task solution:''' |
|||
One feature of this solution is that if you can rely on the input bearings being in the range -180 to 180, you don't have to use math.Mod. Another feature is the bearing type and method syntax. |
|||
<lang go>package main |
|||
import "fmt" |
|||
type bearing float64 |
|||
var testCases = []struct{ b1, b2 bearing }{ |
|||
{20, 45}, |
|||
{-45, 45}, |
|||
{-85, 90}, |
|||
{-95, 90}, |
|||
{-45, 125}, |
|||
{-45, 145}, |
|||
{29.4803, -88.6381}, |
|||
{-78.3251, -159.036}, |
|||
} |
|||
func main() { |
|||
for _, tc := range testCases { |
|||
fmt.Println(tc.b2.Sub(tc.b1)) |
|||
} |
|||
} |
|||
func (b2 bearing) Sub(b1 bearing) bearing { |
|||
switch d := b2 - b1; { |
|||
case d < -180: |
|||
return d + 360 |
|||
case d > 180: |
|||
return d - 360 |
|||
default: |
|||
return d |
|||
} |
|||
}</lang> |
|||
{{out}} |
|||
<pre> |
|||
25 |
|||
90 |
|||
175 |
|||
-175 |
|||
170 |
|||
-170 |
|||
-118.1184 |
|||
-80.7109 |
|||
</pre> |
|||
'''Optional extra solution:''' |
|||
A feature here is that the function body is a one-liner sufficient for the task test cases. |
|||
<lang go>package main |
|||
import ( |
|||
"fmt" |
|||
"math" |
|||
) |
|||
var testCases = []struct{ b1, b2 float64 }{ |
|||
{20, 45}, |
|||
{-45, 45}, |
|||
{-85, 90}, |
|||
{-95, 90}, |
|||
{-45, 125}, |
|||
{-45, 145}, |
|||
{29.4803, -88.6381}, |
|||
{-78.3251, -159.036}, |
|||
{-70099.74233810938, 29840.67437876723}, |
|||
{-165313.6666297357, 33693.9894517456}, |
|||
{1174.8380510598456, -154146.66490124757}, |
|||
{60175.77306795546, 42213.07192354373}, |
|||
} |
|||
func main() { |
|||
for _, tc := range testCases { |
|||
fmt.Println(angleDifference(tc.b2, tc.b1)) |
|||
} |
|||
} |
|||
func angleDifference(b2, b1 float64) float64 { |
|||
return math.Mod(math.Mod(b2-b1, 360)+360+180, 360) - 180 |
|||
}</lang> |
|||
{{out}} |
|||
<pre> |
|||
25 |
|||
90 |
|||
175 |
|||
-175 |
|||
170 |
|||
-170 |
|||
-118.11840000000001 |
|||
-80.71089999999998 |
|||
-139.58328312338563 |
|||
-72.34391851868713 |
|||
-161.50295230740448 |
|||
37.29885558826936 |
|||
</pre> |
</pre> |
||