Search code examples
pythonnumpyangle

Create a circle array of angles to not consider euclidean distance python


I am trying to create a transition matric using this code:

transition_matrix[0:720,:] = (1 / np.sqrt(2 * np.pi * sigma_n2)) * np.exp(-( np.abs(eventspace_psi_i_min_1 - eventspace_psi_i) )**2 / (2 * sigma_n2))

where the formula after it is just the Gaussian distribution.

The eventspaces are arrays of 720 elements, all of which are supposed to angles starting from 0,0.5,...,359.5. Knowing how close 0° and 359.5° are, a non-zero value should appear in the transition matrix for this calculation. But, because of Eucidean distance, it returns 0.

I tried switching up the eventspaces and making them: 0, 0.5,...,180,179.5,...,0,5 but it doesn't work because again of Eukidean distance, since it will give a non-zero when considering 90° and the equivalent for 270° (which is 90 in this case).

In order for this to perform properly, I need to have the angle values in a circle as they would usually appear in a diagram.

Can anyone help me understand how this can be done?


Solution

  • I'm a bit puzzled because you're using degrees, not radians, however if you want an angular distance with the property 0 ≤ δ ≤ 180 you can go like this

    def distance(φ, θ):
        from numpy import abs
        δ = abs(φ-θ)         #    0 ≤ δ < 360
        δ[δ>=180] -= 360     # -180 ≤ δ < 180
        return abs(δ)        #    0 ≤ δ ≤ 180
    

    edit

    Your angles are in the [0, 360) interval, but this is not always the case, so it's better to normalize them, moreover if the arguments are both scalars a TypeError is raised, so it's better to envelope the 360 decrement into a try except clause.

    def distance(φ, θ):
        from numpy import abs
        δ = abs(φ%360 - θ%360)  #    0 ≤ δ < 360
        try:
            δ[δ>=180] -= 360    # -180 ≤ δ < 180
        except TypeError:
            if δ >= 180 : δ -= 360
       return abs(δ)            #    0 ≤ δ ≤ 180