I have wind direction data coming from a weather vane, and the data is represented in 0 to 359 degrees.
I want to convert this into text format (compass rose) with 16 di
Watch out for rounding, angles between 349...11 should be "N", therefore add half sector first (+(360/16)/2), then handle overflow over 360 by %360, then divide by 360/16:
["N","NNW",...,"NNE"][((d+(360/16)/2)%360)/(360/16)]
I believe it is easier to:
DirTable = ["N","NNE","NE","ENE","E","ESE", "SE","SSE","S","SSW","SW","WSW", "W","WNW","NW","NNW",**"N"**];
wind_direction= DirTable[Math.floor((d+11.25)/22.5)];
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 :
Here's a one-line python function:
def deg_to_text(deg):
return ["N","NNE","NE","ENE","E","ESE", "SE", "SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"][round(deg/22.5)%16]
Obviously it can be split into multiple lines for readability/pep8
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.
Javascript function 100% working
function degToCompass(num) {
while( num < 0 ) num += 360 ;
while( num >= 360 ) num -= 360 ;
val= Math.round( (num -11.25 ) / 22.5 ) ;
arr=["N","NNE","NE","ENE","E","ESE", "SE",
"SSE","S","SSW","SW","WSW","W","WNW","NW","NNW"] ;
return arr[ Math.abs(val) ] ;
}
steps
Hope it helps