Created
June 7, 2015 16:18
-
-
Save RobertSudwarts/acf8df23a16afdb5837f to your computer and use it in GitHub Desktop.
[python] degrees to cardinal directions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def degrees_to_cardinal(d): | |
''' | |
note: this is highly approximate... | |
''' | |
dirs = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", | |
"S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"] | |
ix = int((d + 11.25)/22.5) | |
return dirs[ix % 16] |
@mattarderne this is because the result of round
in Python 2 is a float
while the returned value is an int
in Python 3.
See: https://docs.python.org/2/library/functions.html#round and https://docs.python.org/3/library/functions.html#round.
Python 2:
If ndigits is omitted, it defaults to zero. The result is a floating point number.
Python 3:
If ndigits is omitted or is None, it returns the nearest integer to its input.
Thank you, I am going to use this is my project
Thank you. Will use this in my project.
In case someone want's to apply for a Numpy Array of angles I've adapted as such...
def degrees_to_cardinal(d):
'''
note: this is highly approximate...
'''
dirs = np.array(["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
"S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"], dtype='U')
ix = np.round(d / (360. / len(dirs))).astype('i')
return dirs[ix % 16]
I did the following:
DIRECTIONS = [
'N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW',
'W', 'WNW', 'NW', 'NNW', 'N'
]
x = 155 # anything 0 - 360
cardinal = DIRECTIONS[round(x / 22.5)]
Note the extra N
at the end of the list.
This should probably be made a package
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Haven't investigated too carefully but I needed
ix
to be anint
ieThanks