jblas-project / jblas

Linear Algebra for Java
http://jblas.org
BSD 3-Clause "New" or "Revised" License
590 stars 149 forks source link

Implement four-quadrant inverse tangent #124

Open DrNjitram opened 3 years ago

DrNjitram commented 3 years ago

Implement an alternative version of the inverse tangent, which allows one to calculate the angle of a point in the full range of angles (domain: [-pi pi] compared to the normal inverse tangent (domain [-pi/2 pi/2]).

More information: https://nl.mathworks.com/help/matlab/ref/atan2.html and https://en.wikipedia.org/wiki/Atan2

DrNjitram commented 3 years ago

I have currently created a very simple version that works with the already implemented functions. I am sure there is a faster way to do this, but this 'just works'.

public static FloatMatrix atan2(FloatMatrix x, FloatMatrix y){     

        FloatMatrix intermediate = sqrt(x.mul(x).add(y.mul(y)));

        FloatMatrix domainOne = atan(y.div(intermediate.add(x))).mul(2);
        FloatMatrix domainTwo = atan(intermediate.sub(x).div(y)).mul(2);

        FloatMatrix result = new FloatMatrix(x.getRows());

        for(int index : x.gt(0).findIndices()) result.put(index, domainOne.get(index));
        for(int index : x.le(0).and(y.ne(0)).findIndices()) result.put(index, domainTwo.get(index));
        for(int index : x.lt(0).and(y.eq(0)).findIndices()) result.put(index, (float) Math.PI);
        for(int index : x.eq(0).and(y.eq(0)).findIndices()) result.put(index, Float.NaN);

        return result;
    }