2

How can I calculate the difference (WD_Bias) in two wind directions (in degrees) in python so that the results range from -180 to 180? Here is the code I have so far? Does this seem to do what I want or am I missing something else?

WD_Bias = WD_model - WD_obs

WD_Bias[WD_Bias>180.]=360.-WD_Bias[WD_Bias>180.]
WD_Bias[WD_Bias<-180.]=WD_Bias[WD_Bias<-180.]+360.
1
  • 1
    Velocity is a vector quantity. I'd use vectors to find the resultant of two wind directions.
    – duffymo
    Commented Nov 29, 2016 at 10:13

2 Answers 2

3

If the wind directions that you are subtracting are the same magnitude, take the difference and use modulo arithmetic to get your answer between -180 and +180.

If they are different magnitudes, represent those as vectors (real+image works) then use inverse tangent to find the vector difference angle. Or use np.angle. https://docs.scipy.org/doc/numpy/reference/generated/numpy.angle.html

3
  • 1
    What the same magnitude are you talking about? Wind directions given in degrees are scalars. They (directions) might be considered as (unit) vectors to apply atan2 approach, but different magnitudes is nonsense here.
    – MBo
    Commented Nov 29, 2016 at 4:47
  • Wind velocity is a vector with a magnitude (speed) and direction (angle) component.
    – IceArdor
    Commented Dec 5, 2016 at 9:31
  • Difference of wind directions doesn't depend on magnitudes
    – MBo
    Commented Dec 5, 2016 at 10:10
2

If you want errors ranging from 0 to 180 you can use the following function :

import numpy as np

def wdir_diff(wd1,wd2):
    diff1 = (wd1 - wd2)% 360
    diff2 = (wd2 - wd1)% 360
    res = np.minimum([diff1,diff2])
    return res

The following lines should provide insurance that the function produce the expected behavior:

import numpy as np
import matplotlib.pyplot as plt

w1 = np.arange(0,360,5)
w2 = np.arange(0,360,5)
X,Y = np.meshgrid(w1,w2)
Z = wdir_diff(X,Y)

fig, ax = plt.subplots()
ax.set_aspect("equal")
im= ax.pcolormesh(X,Y,Z, cmap="jet")
fig.colorbar(im)
plt.show()  
1
  • I think that should be: res = np.minimum(diff1, diff2)
    – Tomaquet
    Commented May 8, 2023 at 15:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.