Example usage for java.lang Math atan2

List of usage examples for java.lang Math atan2

Introduction

In this page you can find the example usage for java.lang Math atan2.

Prototype

@HotSpotIntrinsicCandidate
public static double atan2(double y, double x) 

Source Link

Document

Returns the angle theta from the conversion of rectangular coordinates ( x ,  y ) to polar coordinates (r, theta).

Usage

From source file:devlight.io.library.ArcProgressStackView.java

@Override
protected void onDraw(final Canvas canvas) {
    super.onDraw(canvas);

    // Save and rotate to start angle
    canvas.save();/*from   w w  w . j ava  2s.co m*/
    final float radius = mSize * 0.5F;
    canvas.rotate(mStartAngle, radius, radius);

    // Draw all of progress
    for (int i = 0; i < mModels.size(); i++) {
        final Model model = mModels.get(i);
        // Get progress for current model
        float progressFraction = mIsAnimated && !isInEditMode()
                ? (model.mLastProgress + (mAnimatedFraction * (model.getProgress() - model.mLastProgress)))
                        / MAX_PROGRESS
                : model.getProgress() / MAX_PROGRESS;
        if (i != mActionMoveModelIndex && mActionMoveModelIndex != ANIMATE_ALL_INDEX)
            progressFraction = model.getProgress() / MAX_PROGRESS;
        final float progress = progressFraction * mSweepAngle;

        // Check if model have gradient
        final boolean isGradient = model.getColors() != null;
        // Set width of progress
        mProgressPaint.setStrokeWidth(mProgressModelSize);

        // Set model arc progress
        model.mPath.reset();
        model.mPath.addArc(model.mBounds, 0.0F, progress);

        // Draw gradient progress or solid
        resetShadowLayer();
        mProgressPaint.setShader(null);
        mProgressPaint.setStyle(Paint.Style.STROKE);

        if (mIsModelBgEnabled) {
            //noinspection ResourceAsColor
            mProgressPaint.setColor(isInEditMode() ? mPreviewModelBgColor : model.getBgColor());
            canvas.drawArc(model.mBounds, 0.0F, mSweepAngle, false, mProgressPaint);
            if (!isInEditMode())
                mProgressPaint.clearShadowLayer();
        }

        // Check if gradient for draw shadow at first and then gradient progress
        if (isGradient) {
            if (!mIsModelBgEnabled) {
                canvas.drawPath(model.mPath, mProgressPaint);

                if (!isInEditMode())
                    mProgressPaint.clearShadowLayer();
            }

            mProgressPaint.setShader(model.mSweepGradient);
        } else
            mProgressPaint.setColor(model.getColor());

        // Here we draw main progress
        mProgressPaint.setAlpha(255);
        canvas.drawPath(model.mPath, mProgressPaint);

        // Preview mode
        if (isInEditMode())
            continue;

        // Get model title bounds
        mTextPaint.setTextSize(mProgressModelSize * 0.5F);
        mTextPaint.getTextBounds(model.getTitle(), 0, model.getTitle().length(), model.mTextBounds);

        // Draw title at start with offset
        final float titleHorizontalOffset = model.mTextBounds.height() * 0.5F;
        final float progressLength = (float) (Math.PI / 180.0F) * progress * model.mBounds.width() * 0.5F;
        final String title = (String) TextUtils.ellipsize(model.getTitle(), mTextPaint,
                progressLength - titleHorizontalOffset * 2, TextUtils.TruncateAt.END);
        canvas.drawTextOnPath(title, model.mPath, mIsRounded ? 0.0F : titleHorizontalOffset,
                titleHorizontalOffset, mTextPaint);

        // Get pos and tan at final path point
        model.mPathMeasure.setPath(model.mPath, false);
        model.mPathMeasure.getPosTan(model.mPathMeasure.getLength(), model.mPos, model.mTan);

        // Get title width
        final float titleWidth = model.mTextBounds.width();

        // Create model progress like : 23%
        final String percentProgress = String.format("%d%%", (int) model.getProgress());
        // Get progress text bounds
        mTextPaint.setTextSize(mProgressModelSize * 0.35f);
        mTextPaint.getTextBounds(percentProgress, 0, percentProgress.length(), model.mTextBounds);

        // Get pos tan with end point offset and check whether the rounded corners for offset
        final float progressHorizontalOffset = mIndicatorOrientation == IndicatorOrientation.VERTICAL
                ? model.mTextBounds.height() * 0.5F
                : model.mTextBounds.width() * 0.5F;
        final float indicatorProgressOffset = (mIsRounded ? progressFraction : 1.0F)
                * (-progressHorizontalOffset - titleHorizontalOffset
                        - (mIsRounded ? model.mTextBounds.height() * 2.0F : 0.0F));
        model.mPathMeasure.getPosTan(model.mPathMeasure.getLength() + indicatorProgressOffset, model.mPos,
                mIndicatorOrientation == IndicatorOrientation.VERTICAL && !mIsRounded ? new float[2]
                        : model.mTan);

        // Check if there available place for indicator
        if ((titleWidth + model.mTextBounds.height() + titleHorizontalOffset * 2.0F)
                - indicatorProgressOffset < progressLength) {
            // Get rotate indicator progress angle for progress value
            float indicatorProgressAngle = (float) (Math.atan2(model.mTan[1], model.mTan[0])
                    * (180.0F / Math.PI));
            // Get arc angle of progress indicator
            final float indicatorLengthProgressAngle = ((progressLength + indicatorProgressOffset)
                    / (model.mBounds.width() * 0.5F)) * (float) (180.0F / Math.PI);

            // Detect progress indicator position : left or right and then rotate
            if (mIndicatorOrientation == IndicatorOrientation.VERTICAL) {
                // Get X point of arc angle progress indicator
                final float x = (float) (model.mBounds.width() * 0.5F
                        * (Math.cos((indicatorLengthProgressAngle + mStartAngle) * Math.PI / 180.0F)))
                        + model.mBounds.centerX();
                indicatorProgressAngle += (x > radius) ? -90.0F : 90.0F;
            } else {
                // Get Y point of arc angle progress indicator
                final float y = (float) (model.mBounds.height() * 0.5F
                        * (Math.sin((indicatorLengthProgressAngle + mStartAngle) * Math.PI / 180.0F)))
                        + model.mBounds.centerY();
                indicatorProgressAngle += (y > radius) ? 180.0F : 0.0F;
            }

            // Draw progress value
            canvas.save();
            canvas.rotate(indicatorProgressAngle, model.mPos[0], model.mPos[1]);
            canvas.drawText(percentProgress, model.mPos[0] - model.mTextBounds.exactCenterX(),
                    model.mPos[1] - model.mTextBounds.exactCenterY(), mTextPaint);
            canvas.restore();
        }

        // Check if gradient and have rounded corners, because we must to create elevation effect
        // for start progress corner
        if ((isGradient || mIsLeveled) && mIsRounded && progress != 0) {
            model.mPathMeasure.getPosTan(0.0F, model.mPos, model.mTan);

            // Set paint for overlay rounded gradient with shadow
            setLevelShadowLayer();
            //noinspection ResourceAsColor
            mLevelPaint.setColor(isGradient ? model.getColors()[0] : model.getColor());

            // Get bounds of start pump
            final float halfSize = mProgressModelSize * 0.5F;
            final RectF arcRect = new RectF(model.mPos[0] - halfSize, model.mPos[1] - halfSize,
                    model.mPos[0] + halfSize, model.mPos[1] + halfSize + 2.0F);
            canvas.drawArc(arcRect, 0.0F, -180.0F, true, mLevelPaint);
        }
    }

    // Restore after drawing
    canvas.restore();
}

From source file:edu.uci.ics.jung.visualization.PluggableRenderer.java

/**
 * This is used for the arrow of a directed and for one of the
 * arrows for non-directed edges// ww  w .ja  va2s. c  o m
 * Get a transform to place the arrow shape on the passed edge at the
 * point where it intersects the passed shape
 * @param edgeShape
 * @param vertexShape
 * @return
 */
public AffineTransform getArrowTransform(Line2D edgeShape, Shape vertexShape) {
    float dx = (float) (edgeShape.getX1() - edgeShape.getX2());
    float dy = (float) (edgeShape.getY1() - edgeShape.getY2());
    // iterate over the line until the edge shape will place the
    // arrowhead closer than 'arrowGap' to the vertex shape boundary
    while ((dx * dx + dy * dy) > arrow_placement_tolerance) {
        try {
            edgeShape = getLastOutsideSegment(edgeShape, vertexShape);
        } catch (IllegalArgumentException e) {
            System.err.println(e.toString());
            return null;
        }
        dx = (float) (edgeShape.getX1() - edgeShape.getX2());
        dy = (float) (edgeShape.getY1() - edgeShape.getY2());
    }
    double atheta = Math.atan2(dx, dy) + Math.PI / 2;
    AffineTransform at = AffineTransform.getTranslateInstance(edgeShape.getX1(), edgeShape.getY1());
    at.rotate(-atheta);
    return at;
}

From source file:org.esa.s1tbx.fex.gpf.oceantools.WindFieldEstimationOp.java

/**
 * Estimate wind speed using CMOD5 model.
 *
 * @param nrcs      The normalized radar cross section.
 * @param direction The wind direction vector.
 * @param theta     The incidence angle in degree.
 * @return The wind speed in m/s.//from w w  w .  j ava  2 s  .  co m
 */
private static double estimateWindSpeed(final double nrcs, final double[] direction, final double theta) {

    final double fi = Math.atan2(direction[1], direction[0]) * Constants.RTOD;
    final double cosFI = FastMath.cos(fi * Constants.DTOR);

    // try wind speed from 0.1 m/s to 20 m/s with step size 0.1
    final double[] err = new double[200];
    err[0] = Math.abs(nrcs - CMOD5.compute(0.1, cosFI, theta));
    double errMin = err[0];
    int errMinIndex = 0;
    for (int i = 1; i < 200; i++) {
        final double v = (i + 1) * 0.1; // speed
        err[i] = Math.abs(nrcs - CMOD5.compute(v, cosFI, theta));
        if (err[i] < errMin) {
            errMin = err[i];
            errMinIndex = i;
        }
    }

    return (errMinIndex + 1) * 0.1;
}

From source file:com.rapidminer.tools.expression.internal.function.AntlrParserTrigonometricTest.java

@Test
public void atan2IntInt() {
    try {/*from   ww w.ja v a  2s.com*/
        Expression expression = getExpressionWithFunctionContext("atan2(16,16)");
        assertEquals(ExpressionType.DOUBLE, expression.getExpressionType());
        assertEquals(Math.atan2(16, 16), expression.evaluateNumerical(), 1e-15);
    } catch (ExpressionException e) {
        assertNotNull(e.getMessage());
    }
}

From source file:org.esa.s1tbx.sentinel1.gpf.SpectralDiversityOp.java

private double estimateAzOffsets(final Band mBandI, final Band mBandQ, final Band sBandI, final Band sBandQ,
        final Rectangle backwardRectangle, final Rectangle forwardRectangle, final double spectralSeparation) {

    final int mDataType = mBandI.getDataType();
    final int sDataType = sBandI.getDataType();

    final Tile mTileIBack = getSourceTile(mBandI, backwardRectangle);
    final Tile mTileQBack = getSourceTile(mBandQ, backwardRectangle);
    final Tile sTileIBack = getSourceTile(sBandI, backwardRectangle);
    final Tile sTileQBack = getSourceTile(sBandQ, backwardRectangle);

    double[] mIBackArray, mQBackArray;
    if (mDataType == ProductData.TYPE_INT16) {
        final short[] mIBackArrayShort = (short[]) mTileIBack.getDataBuffer().getElems();
        final short[] mQBackArrayShort = (short[]) mTileQBack.getDataBuffer().getElems();
        mIBackArray = new double[mIBackArrayShort.length];
        mQBackArray = new double[mQBackArrayShort.length];
        for (int i = 0; i < mIBackArrayShort.length; i++) {
            mIBackArray[i] = (double) mIBackArrayShort[i];
            mQBackArray[i] = (double) mQBackArrayShort[i];
        }//from  ww w. ja  v a 2s . c o  m
    } else {
        mIBackArray = (double[]) mTileIBack.getDataBuffer().getElems();
        mQBackArray = (double[]) mTileQBack.getDataBuffer().getElems();
    }

    double[] sIBackArray, sQBackArray;
    if (sDataType == ProductData.TYPE_FLOAT32) {
        final float[] sIBackArrayFloat = (float[]) sTileIBack.getDataBuffer().getElems();
        final float[] sQBackArrayFloat = (float[]) sTileQBack.getDataBuffer().getElems();
        sIBackArray = new double[sIBackArrayFloat.length];
        sQBackArray = new double[sQBackArrayFloat.length];
        for (int i = 0; i < sIBackArrayFloat.length; i++) {
            sIBackArray[i] = (double) sIBackArrayFloat[i];
            sQBackArray[i] = (double) sQBackArrayFloat[i];
        }
    } else {
        sIBackArray = (double[]) sTileIBack.getDataBuffer().getElems();
        sQBackArray = (double[]) sTileQBack.getDataBuffer().getElems();
    }

    final Tile mTileIFor = getSourceTile(mBandI, forwardRectangle);
    final Tile mTileQFor = getSourceTile(mBandQ, forwardRectangle);
    final Tile sTileIFor = getSourceTile(sBandI, forwardRectangle);
    final Tile sTileQFor = getSourceTile(sBandQ, forwardRectangle);

    double[] mIForArray, mQForArray;
    if (mDataType == ProductData.TYPE_INT16) {
        final short[] mIForArrayShort = (short[]) mTileIFor.getDataBuffer().getElems();
        final short[] mQForArrayShort = (short[]) mTileQFor.getDataBuffer().getElems();
        mIForArray = new double[mIForArrayShort.length];
        mQForArray = new double[mQForArrayShort.length];
        for (int i = 0; i < mIForArrayShort.length; i++) {
            mIForArray[i] = (double) mIForArrayShort[i];
            mQForArray[i] = (double) mQForArrayShort[i];
        }
    } else {
        mIForArray = (double[]) mTileIFor.getDataBuffer().getElems();
        mQForArray = (double[]) mTileQFor.getDataBuffer().getElems();
    }

    double[] sIForArray, sQForArray;
    if (sDataType == ProductData.TYPE_FLOAT32) {
        final float[] sIForArrayFloat = (float[]) sTileIFor.getDataBuffer().getElems();
        final float[] sQForArrayFloat = (float[]) sTileQFor.getDataBuffer().getElems();
        sIForArray = new double[sIForArrayFloat.length];
        sQForArray = new double[sQForArrayFloat.length];
        for (int i = 0; i < sIForArrayFloat.length; i++) {
            sIForArray[i] = (double) sIForArrayFloat[i];
            sQForArray[i] = (double) sQForArrayFloat[i];
        }
    } else {
        sIForArray = (double[]) sTileIFor.getDataBuffer().getElems();
        sQForArray = (double[]) sTileQFor.getDataBuffer().getElems();
    }

    final int arrayLength = mIBackArray.length;
    final double[] backIntReal = new double[arrayLength];
    final double[] backIntImag = new double[arrayLength];
    complexArrayMultiplication(mIBackArray, mQBackArray, sIBackArray, sQBackArray, backIntReal, backIntImag);

    final double[] forIntReal = new double[arrayLength];
    final double[] forIntImag = new double[arrayLength];
    complexArrayMultiplication(mIForArray, mQForArray, sIForArray, sQForArray, forIntReal, forIntImag);

    final double[] diffIntReal = new double[arrayLength];
    final double[] diffIntImag = new double[arrayLength];
    complexArrayMultiplication(forIntReal, forIntImag, backIntReal, backIntImag, diffIntReal, diffIntImag);

    double sumReal = 0.0, sumImag = 0.0;
    for (int i = 0; i < arrayLength; i++) {
        final double theta = Math.atan2(diffIntImag[i], diffIntReal[i]);
        sumReal += FastMath.cos(theta);
        sumImag += FastMath.sin(theta);
    }

    final double phase = Math.atan2(sumImag, sumReal);
    return phase / (2 * Math.PI * spectralSeparation * subSwath[subSwathIndex - 1].azimuthTimeInterval);
}

From source file:org.bimserver.GeometryGenerator.java

/**
 * This function should return a transformation matrix (with translation and
 * rotation, no scaling) overlaying triangle V on U Assumed is that the
 * triangles are indeed the same and the order of the vertices is also the
 * same (shifts are not allowed) This function can probably be optimized for
 * speed and also the LOC can probably be reduced
 * /*from w w w. ja v a 2 s  .c  o  m*/
 * @param originalV1
 * @param originalV2
 * @param originalV3
 * @param u1
 * @param u2
 * @param u3
 * @return
 */
private static float[] getTransformationMatrix(float[] originalV1, float[] originalV2, float[] originalV3,
        float[] u1, float[] u2, float[] u3, float maxDiff) {
    float[] v1 = copy(originalV1);
    float[] v2 = copy(originalV2);
    float[] v3 = copy(originalV3);
    u1 = copy(u1);
    u2 = copy(u2);
    u3 = copy(u3);

    float transX = u1[0] - v1[0];
    float transY = u1[1] - v1[1];
    float transZ = u1[2] - v1[2];

    float translation[] = new float[16];
    Matrix.setIdentityM(translation, 0);
    Matrix.translateM(translation, 0, u1[0], u1[1], u1[2]);

    float[] toZeroTranslation = new float[16];
    Matrix.setIdentityM(toZeroTranslation, 0);
    Matrix.translateM(toZeroTranslation, 0, -v1[0], -v1[1], -v1[2]);

    if (almostTheSame(v2[0] + transX, u2[0], maxDiff) && almostTheSame(v2[1] + transY, u2[1], maxDiff)
            && almostTheSame(v2[2] + transZ, u2[2], maxDiff) && almostTheSame(v3[0] + transX, u3[0], maxDiff)
            && almostTheSame(v3[1] + transY, u3[1], maxDiff) && almostTheSame(v3[2] + transZ, u3[2], maxDiff)) {
        // The other two points are already the same, to there was no
        // rotation
        return translation;
    }

    // Normalize both triangles to their first vertex
    subtract(u2, u1);
    subtract(u3, u1);
    subtract(u1, u1);

    subtract(v2, v1);
    subtract(v3, v1);
    subtract(v1, v1);

    float[] u2CrossV2 = Vector.crossProduct(u2, v2);
    float[] r2 = new float[16];
    Matrix.setIdentityM(r2, 0);
    float[] r2v2 = new float[4];
    if (!equalsAlmost(u2, v2, maxDiff)) {
        float u2InV2 = Vector.dot(u2, v2);
        float[] axis = u2CrossV2;
        if (axis[0] == 0 && axis[1] == 0 && axis[2] == 0) {
            axis = new float[] { u2[1], -u2[0], 0, 0 };
        }
        Matrix.rotateM(r2, 0, (float) Math.toDegrees(Math.atan2(Vector.length(u2CrossV2), u2InV2)), axis[0],
                axis[1], axis[2]);

        Matrix.multiplyMV(r2v2, 0, r2, 0, new float[] { v2[0], v2[1], v2[2], 1 }, 0);

        if (!equalsAlmost(r2v2, u2, maxDiff)) {
            Matrix.setIdentityM(r2, 0);
            Matrix.rotateM(r2, 0, -(float) Math.toDegrees(Math.atan2(Vector.length(u2CrossV2), u2InV2)),
                    axis[0], axis[1], axis[2]);
            Matrix.multiplyMV(r2v2, 0, r2, 0, new float[] { v2[0], v2[1], v2[2], 1 }, 0);
            if (!equalsAlmost(r2v2, u2, maxDiff)) {
                return null;
            }
        }
    } else {
        r2v2 = copy(v2);
    }

    float[] r2v3 = new float[4];
    Matrix.multiplyMV(r2v3, 0, r2, 0, new float[] { v3[0], v3[1], v3[2], 1 }, 0);

    float[] r3 = new float[16];
    Matrix.setIdentityM(r3, 0);

    float angleDegrees = (float) Math.toDegrees(getPlaneAngle(v1, r2v2, r2v3, u1, u2, u3));

    Matrix.rotateM(r3, 0, angleDegrees, r2v2[0], r2v2[1], r2v2[2]);

    float[] r3v3 = new float[4];
    Matrix.multiplyMV(r3v3, 0, r3, 0, new float[] { r2v3[0], r2v3[1], r2v3[2], 1 }, 0);

    float[] r2v1 = new float[4];
    Matrix.multiplyMV(r2v1, 0, r2, 0, new float[] { v1[0], v1[1], v1[2], 1 }, 0);

    float[] r3v1 = new float[4];
    Matrix.multiplyMV(r3v1, 0, r3, 0, new float[] { r2v1[0], r2v1[1], r2v1[2], 1 }, 0);

    if (!equalsAlmost(r3v3, u3, maxDiff)) {
        Matrix.setIdentityM(r3, 0);
        Matrix.rotateM(r3, 0, -angleDegrees, r2v2[0], r2v2[1], r2v2[2]);
        Matrix.multiplyMV(r3v3, 0, r3, 0, new float[] { r2v3[0], r2v3[1], r2v3[2], 1 }, 0);
        float[] r3v2 = new float[4];
        Matrix.multiplyMV(r3v2, 0, r3, 0, new float[] { r2v2[0], r2v2[1], r2v2[2], 1 }, 0);
        if (!equalsAlmost(r3v3, u3, maxDiff) || !equalsAlmost(r3v2, u2, maxDiff)) {
            return null;
        }
    }
    float[] subResult = new float[16];
    float[] subResult2 = new float[16];
    float[] subResult3 = new float[16];
    float[] totalResult = new float[16];
    float[] startMatrix = new float[16];
    Matrix.setIdentityM(startMatrix, 0);

    Matrix.multiplyMM(subResult, 0, toZeroTranslation, 0, startMatrix, 0);
    Matrix.multiplyMM(subResult2, 0, r2, 0, subResult, 0);
    Matrix.multiplyMM(subResult3, 0, r3, 0, subResult2, 0);
    Matrix.multiplyMM(totalResult, 0, translation, 0, subResult3, 0);

    return totalResult;
}

From source file:com.rapidminer.tools.expression.internal.function.AntlrParserTrigonometricTest.java

@Test
public void atan2DoubleInt() {
    try {/*  w  w  w . j  a va  2  s.  c o m*/
        Expression expression = getExpressionWithFunctionContext("atan2(16.3,16)");
        assertEquals(ExpressionType.DOUBLE, expression.getExpressionType());
        assertEquals(Math.atan2(16.3, 16), expression.evaluateNumerical(), 1e-15);
    } catch (ExpressionException e) {
        assertNotNull(e.getMessage());
    }
}

From source file:com.rapidminer.tools.expression.internal.function.AntlrParserTrigonometricTest.java

@Test
public void atan2IntDouble() {
    try {//from   w  ww  .  j  a v  a2s  .c  o  m
        Expression expression = getExpressionWithFunctionContext("atan2(16,16.3)");
        assertEquals(ExpressionType.DOUBLE, expression.getExpressionType());
        assertEquals(Math.atan2(16, 16.3), expression.evaluateNumerical(), 1e-15);
    } catch (ExpressionException e) {
        assertNotNull(e.getMessage());
    }
}

From source file:org.chombo.util.BasicUtils.java

/**
 * geo location distance by Haversine formula
 * @param lat1//from   w  ww . j ava 2s .c om
 * @param long1
 * @param lat2
 * @param long2
 * @return distance in km
 */
public static double getGeoDistance(double lat1, double long1, double lat2, double long2) {
    double latDistance = Math.toRadians(lat1 - lat2);
    double longDistance = Math.toRadians(long1 - long2);

    double a = (Math.sin(latDistance / 2) * Math.sin(latDistance / 2)) + (Math.cos(Math.toRadians(lat1)))
            * (Math.cos(Math.toRadians(lat2))) * (Math.sin(longDistance / 2)) * (Math.sin(longDistance / 2));
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return AVERAGE_RADIUS_OF_EARTH * c;

}

From source file:com.rapidminer.tools.expression.internal.function.AntlrParserTrigonometricTest.java

@Test
public void atan2DoubleDouble() {
    try {//from   w  w w .  jav  a2 s  .c om
        Expression expression = getExpressionWithFunctionContext("atan2(33.3,33.3)");
        assertEquals(ExpressionType.DOUBLE, expression.getExpressionType());
        assertEquals(Math.atan2(33.3, 33.3), expression.evaluateNumerical(), 1e-15);
    } catch (ExpressionException e) {
        assertNotNull(e.getMessage());
    }
}