Converting wind direction in angles to text words
EDIT :
Since there is an angle change at every 22.5 degrees, the direction should swap hands after 11.25 degrees.
Therefore:
349-360//0-11 = N
12-33 = NNE
34-56 = NE
Using values from 327-348 (The entire NNW spectrum) failed to produce a result for eudoxos' answer. After giving it some thought I could not find the flaw in his logic, so i rewrote my own..
def degToCompass(num):
val=int((num/22.5)+.5)
arr=["N","NNE","NE","ENE","E","ESE", "SE", "SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"]
print arr[(val % 16)]
>>> degToCompass(0)
N
>>> degToCompass(180)
S
>>> degToCompass(720)
N
>>> degToCompass(11)
N
>>> 12
12
>>> degToCompass(12)
NNE
>>> degToCompass(33)
NNE
>>> degToCompass(34)
NE
STEPS :
- Divide the angle by 22.5 because 360deg/16 directions = 22.5deg/direction change.
- Add .5 so that when you truncate the value you can break the 'tie' between the change threshold.
- Truncate the value using integer division (so there is no rounding).
- Directly index into the array and print the value (mod 16).
Here's a javascript implementation of steve-gregory's answer, which works for me.
function degToCompass(num) {
var val = Math.floor((num / 22.5) + 0.5);
var arr = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"];
return arr[(val % 16)];
}
See his answer for an explanation of the logic.
This JavaScript will work for anyone who only needs 8 cardinal directions and would like corresponding arrows.
function getCardinalDirection(angle) {
const directions = ['↑ N', '↗ NE', '→ E', '↘ SE', '↓ S', '↙ SW', '← W', '↖ NW'];
return directions[Math.round(angle / 45) % 8];
}