39

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 different directions.

Basically I want to know if there is a fast slick way to scale the angle reading to a 16 string array to print out the correct wind direction without using a bunch of if statements and checking for ranges of angles

Wind direction can be found here.

thanks!

Matt Frear
  • 45,587
  • 10
  • 66
  • 82
zacharoni
  • 393
  • 1
  • 3
  • 4
  • 1
    Are looking for text to the tune of N, NNW, NW, WNW, etc? – Joseph Sep 20 '11 at 19:31
  • 1
    The link in the question is now broken – ferpel Feb 13 '19 at 18:32
  • If you're looking for the opposite conversion (compass directions to numeric degrees) as I was, here's an answer: https://stackoverflow.com/questions/42597344/convert-from-compass-direcitions-to-degrees-r – DirtStats Mar 02 '20 at 17:31

15 Answers15

79

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 :

  1. Divide the angle by 22.5 because 360deg/16 directions = 22.5deg/direction change.
  2. Add .5 so that when you truncate the value you can break the 'tie' between the change threshold.
  3. Truncate the value using integer division (so there is no rounding).
  4. Directly index into the array and print the value (mod 16).
steve-gregory
  • 7,036
  • 7
  • 34
  • 47
  • Why are you subtracting 1 here? That would seem to give you -1 for the event of 0 degrees, giving you an index out of bounds error. Other than that, exactly what I was thinking. – Joseph Sep 20 '11 at 19:37
  • Remove the subtract 1 and put in the value 359. IndexOutOfBounds error. I did a subtract 1 and left out a tiny check.. If < 0, index should be set to 0. – steve-gregory Sep 20 '11 at 19:39
33

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.

Community
  • 1
  • 1
Matt Frear
  • 45,587
  • 10
  • 66
  • 82
  • What does `Math.floor(n + 0.5)` do differently from `Math.round(n)`? Is it more performant? – Nick Schild Nov 06 '19 at 17:22
  • It wasn't for performance reasons... maybe `Math.round(n)` would work fine. It would be worth trying with unit tests. – Matt Frear Nov 07 '19 at 21:58
  • Ha ha, I wrote this then went to post it here and saw yours, personally I would move the %16 up into the first calculation .. – Mike Q Apr 19 '20 at 20:38
11

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)]
DoubleMalt
  • 1,183
  • 10
  • 16
eudoxos
  • 17,278
  • 9
  • 48
  • 94
  • Aapparently none of fellows posters did :-( [They should all get a F for their answers, sice 359 should be clearly N, but they will get NNE or such.] – eudoxos Sep 21 '11 at 14:21
  • @eudoxos: The divisor at the end should be 360/16 . Corrected the answer above. Works now. You might need a Math.floor or something similar in most languages though. – DoubleMalt Sep 28 '12 at 15:15
  • 1
    Thank you @DoubleMalt, if anyone is getting N at 359 and NNE at 1, use `[Math.floor(((d+(360/16)/2)%360)/(360/16))]` – BillyNair Feb 13 '17 at 11:18
  • 1
    Watch out if you are using this in Python 2. It had me stumped wondering why it wasn't working quite right. This is using integer division, and needs to have at least one side of every division be a float for this to work. Replacing both instances of (360/16) with (360.0/16) will make it work correctly. – jmpreiks Mar 20 '17 at 13:40
6

I checked this and it works very good and seems accurate. Source: http://www.themethodology.net/2013/12/how-to-convert-degrees-to-cardinal.html by Adrian Stevens

    public static string DegreesToCardinal(double degrees)
    {
        string[] caridnals = { "N", "NE", "E", "SE", "S", "SW", "W", "NW", "N" };
        return caridnals[(int)Math.Round(((double)degrees % 360) / 45)];
    }

    public static string DegreesToCardinalDetailed(double degrees)
    {
        degrees *= 10;

        string[] caridnals = { "N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW", "N" };
        return caridnals[(int)Math.Round(((double)degrees % 3600) / 225)];
    }
user2675312
  • 61
  • 1
  • 2
6

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];
}
Edward Brey
  • 35,877
  • 14
  • 173
  • 224
4

I believe it is easier to:

  1. Shift the direction by 11.25
  2. Add an "N" at the end of the direction list to handle the 'over 360',

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)];
Baz
  • 34,567
  • 11
  • 66
  • 88
edom-plc
  • 41
  • 1
2

To do the reverse conversion (compass letter abbreviations to degrees):

function getDir($b)
{

   $dirs = array('N'=>0, 'NNE'=>22.5,"NE"=>45,"ENE"=>67.5, 'E'=>90,'ESE'=>112.5, 'SE'=>135,'SSE'=>157.5, 'S'=>180,'SSW'=>202.5, 'SW'=>225,'WSW'=>247.5, 'W'=>270,'WNW'=>292.5,'NW'=>315,'NNW'=>337.5, 'N'=>0,'North'=>0,'East'=>90,'West'=>270,'South'=>180);
   return $dirs[$b];
}
DirtStats
  • 409
  • 6
  • 26
Arne Kaas
  • 119
  • 1
  • 1
2

this works fine

#!/usr/bin/env python

def wind_deg_to_str1(deg):
        if   deg >=  11.25 and deg <  33.75: return 'NNE'
        elif deg >=  33.75 and deg <  56.25: return 'NE'
        elif deg >=  56.25 and deg <  78.75: return 'ENE'
        elif deg >=  78.75 and deg < 101.25: return 'E'
        elif deg >= 101.25 and deg < 123.75: return 'ESE'
        elif deg >= 123.75 and deg < 146.25: return 'SE'
        elif deg >= 146.25 and deg < 168.75: return 'SSE'
        elif deg >= 168.75 and deg < 191.25: return 'S'
        elif deg >= 191.25 and deg < 213.75: return 'SSW'
        elif deg >= 213.75 and deg < 236.25: return 'SW'
        elif deg >= 236.25 and deg < 258.75: return 'WSW'
        elif deg >= 258.75 and deg < 281.25: return 'W'
        elif deg >= 281.25 and deg < 303.75: return 'WNW'
        elif deg >= 303.75 and deg < 326.25: return 'NW'
        elif deg >= 326.25 and deg < 348.75: return 'NNW'
        else: return 'N'

def wind_deg_to_str2(deg):
        arr = ['NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N']
        return arr[int(abs((deg - 11.25) % 360)/ 22.5)]

i = 0
while i < 360:
        s1 = wind_deg_to_str1(i)
        s2 = wind_deg_to_str2(i)
        print '%5.1f deg -> func1(%-3s), func2(%-3s), same:%s' % (i, s1, s2, ('ok' if s1 == s2 else 'different'))
        i += 0.5
2

If you arrived here and are only interested in breaking your degrees into one of 8 directions.

function degToCompass(num){
    const val =  Math.floor((num / 45) + 0.5);
    const arr = ["N","NE","E", "SE","S","SW","W","NW"];
    return arr[(val % 8)]
Enda Molloy
  • 850
  • 7
  • 18
2

I would probably just do simple division of degrees to get a position in an array or an enum value or something that would give you the text you need. Just round down on all your division. 360/16 = 22.5, so you would want to divide by 22.5 to get the position.

String[] a = [N,NNW,NW,WNW,...,NNE]

Joseph
  • 1,351
  • 19
  • 44
1

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

  1. Given a 360 degree angle
  2. Since north is between -11.25 to 11.25 we subtract 11.25 for accuracy
  3. Divide the angle by 22.5 because 360deg/16 directions = 22.5deg/direction change
  4. Math.abs for as negative is still north
  5. Select the segment from arr from answer

Hope it helps

Pascal
  • 2,172
  • 3
  • 21
  • 38
  • It doesn't work. degToCompass(70) returns NNE, the correct answer is ENE. http://www.climate.umn.edu/snow_fence/components/winddirectionanddegreeswithouttable3.htm – Matt Frear Sep 16 '14 at 10:33
  • 1
    more testing needed! -90 should be west not east, also 12 degrees should be the first transition away from north. – Sam Mason Apr 23 '15 at 18:56
  • @SamMason the function was created to work for angles between 0 to 360. i have modified to work with any now Thanks for input – Pascal May 08 '15 at 08:02
1

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

Hack5
  • 1,889
  • 15
  • 24
0

Used this in Excel: VLOOKUP(MROUND(N12,22.5),N14:O29,2,FALSE)

Cell N12 is direction toward in degrees for which an answer is needed. The range N14:O29 is looking up the sector(A to R):

WIND SECTOR 0 A 22.5 B 45 C 67.5 D 90 E 112.5 F 135 G 157.5 H 180 J 202.5 K 225 L 247.5 M 270 N 292.5 P 315 Q 337.5 R

0

I use R heavily and needed a solution for this. This is what I came up with and works well for all possible combinations I have fed it:

degToCardinal <- function(degrees) {
  val <- as.integer((degrees / 22.5) + 0.5)
  arr <- c("N","NNE","NE","ENE","E","ESE", "SE", "SSE","S","SSW","SW","WSW","W","WNW","NW","NNW")
  return(arr[((val+1) %% 16)])
}
azdatasci
  • 701
  • 1
  • 9
  • 27
0

Wanted to use @eudoxos but needed to pull all the parts together:

def deg_to_compass(d):
  return ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
        "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"] [math.floor(((d+(360/16)/2)%360)/(360/16))]

Borrrowed @Hristo markow to check the results:

for i in range(0,360):
  print (i,deg_to_compass(i) == wind_deg_to_str2(i))
Bruce
  • 71
  • 3