vendredi 5 mai 2017

Convert "strange" ternary operator from java-script to python

I am converting a code from java-script (I am beginner) to python (intermediate level). The code involves an if statement under the form of a Conditional (ternary) Operator.

The line of code is this:

// if dLon over 180° take shorter rhumb line across the anti-meridian:
if (Math.abs(Δλ) > Math.PI) Δλ = Δλ>0 ? -(2*Math.PI-Δλ) : (2*Math.PI+Δλ);

I know the definition of ternary operator which is the following:

condition ? expr1 : expr2

However, my code as an extra "condition" which I don't know how to interpret: Δλ = Δλ>0

At the moment my python version looks like this:

import numpy as np
# note: delta_lon = Δλ
if np.abs(delta_lon) > np.pi:
            delta_lon = -(2*np.pi - delta_lon)
        else:
            delta_lon = 2*np.pi + delta_lon

but it seems to give wrong results. I guess the issue is given by the "condition" mentioned previously and by the fact I am redefining the variable delta_lon.

The entire code can be found under the section rhumb line distance in this link.

EDIT: here is the complete code I am trying to convert from javascript:

var Δψ = Math.log(Math.tan(Math.PI/4+φ2/2)/Math.tan(Math.PI/4+φ1/2));
var q = Math.abs(Δψ) > 10e-12 ? Δφ/Δψ : Math.cos(φ1); // E-W course becomes ill-conditioned with 0/0

// if dLon over 180° take shorter rhumb line across the anti-meridian:
if (Math.abs(Δλ) > Math.PI) Δλ = Δλ>0 ? -(2*Math.PI-Δλ) : (2*Math.PI+Δλ);

var dist = Math.sqrt(Δφ*Δφ + q*q*Δλ*Δλ) * R;

I was able to convert almost the whole code except the if statement previously mentioned. If I do not write the statement, my python code returns the same result as the javascript code (which is ok just because I am using good input values...). However if I add the lines that I presented above, I do not get the same result anymore, which indicates that the ternary operator has been translated in the wrong way.

Aucun commentaire:

Enregistrer un commentaire