Example usage for java.lang Math sin

List of usage examples for java.lang Math sin

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public static double sin(double a) 

Source Link

Document

Returns the trigonometric sine of an angle.

Usage

From source file:edu.stanford.slac.archiverappliance.PB.data.BoundaryConditionsSimulationValueGenerator.java

/**
 * Get a value based on the DBR type. //from w  w  w  .  j  a va2 s .  c om
 * We should check for boundary conditions here and make sure PB does not throw exceptions when we come close to MIN_ and MAX_ values 
 * @param type
 * @param secondsIntoYear
 * @return
 */
public SampleValue getSampleValue(ArchDBRTypes type, int secondsIntoYear) {
    switch (type) {
    case DBR_SCALAR_STRING:
        return new ScalarStringSampleValue(Integer.toString(secondsIntoYear));
    case DBR_SCALAR_SHORT:
        if (0 <= secondsIntoYear && secondsIntoYear < 1000) {
            // Check for some numbers around the minimum value
            return new ScalarValue<Short>((short) (Short.MIN_VALUE + secondsIntoYear));
        } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) {
            // Check for some numbers around the maximum value
            return new ScalarValue<Short>((short) (Short.MAX_VALUE - (secondsIntoYear - 1000)));
        } else {
            // Check for some numbers around 0
            return new ScalarValue<Short>((short) (secondsIntoYear - 2000));
        }
    case DBR_SCALAR_FLOAT:
        if (0 <= secondsIntoYear && secondsIntoYear < 1000) {
            // Check for some numbers around the minimum value
            return new ScalarValue<Float>(Float.MIN_VALUE + secondsIntoYear);
        } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) {
            // Check for some numbers around the maximum value
            return new ScalarValue<Float>(Float.MAX_VALUE - (secondsIntoYear - 1000));
        } else {
            // Check for some numbers around 0. Divide by a large number to make sure we cater to the number of precision digits
            return new ScalarValue<Float>((secondsIntoYear - 2000.0f) / secondsIntoYear);
        }
    case DBR_SCALAR_ENUM:
        return new ScalarValue<Short>((short) secondsIntoYear);
    case DBR_SCALAR_BYTE:
        return new ScalarValue<Byte>(((byte) (secondsIntoYear % 255)));
    case DBR_SCALAR_INT:
        if (0 <= secondsIntoYear && secondsIntoYear < 1000) {
            // Check for some numbers around the minimum value
            return new ScalarValue<Integer>(Integer.MIN_VALUE + secondsIntoYear);
        } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) {
            // Check for some numbers around the maximum value
            return new ScalarValue<Integer>(Integer.MAX_VALUE - (secondsIntoYear - 1000));
        } else {
            // Check for some numbers around 0
            return new ScalarValue<Integer>(secondsIntoYear - 2000);
        }
    case DBR_SCALAR_DOUBLE:
        if (0 <= secondsIntoYear && secondsIntoYear < 1000) {
            // Check for some numbers around the minimum value
            return new ScalarValue<Double>(Double.MIN_VALUE + secondsIntoYear);
        } else if (1000 <= secondsIntoYear && secondsIntoYear < 2000) {
            // Check for some numbers around the maximum value
            return new ScalarValue<Double>(Double.MAX_VALUE - (secondsIntoYear - 1000));
        } else {
            // Check for some numbers around 0. Divide by a large number to make sure we cater to the number of precision digits
            return new ScalarValue<Double>((secondsIntoYear - 2000.0) / (secondsIntoYear * 1000000));
        }
    case DBR_WAVEFORM_STRING:
        // Varying number of copies of a typical value
        return new VectorStringSampleValue(
                Collections.nCopies(secondsIntoYear, Integer.toString(secondsIntoYear)));
    case DBR_WAVEFORM_SHORT:
        return new VectorValue<Short>(Collections.nCopies(1, (short) secondsIntoYear));
    case DBR_WAVEFORM_FLOAT:
        // Varying number of copies of a typical value
        return new VectorValue<Float>(
                Collections.nCopies(secondsIntoYear, (float) Math.cos(secondsIntoYear * Math.PI / 3600)));
    case DBR_WAVEFORM_ENUM:
        return new VectorValue<Short>(Collections.nCopies(1024, (short) secondsIntoYear));
    case DBR_WAVEFORM_BYTE:
        // Large number of elements in the array
        return new VectorValue<Byte>(
                Collections.nCopies(65536 * secondsIntoYear, ((byte) (secondsIntoYear % 255))));
    case DBR_WAVEFORM_INT:
        // Varying number of copies of a typical value
        return new VectorValue<Integer>(
                Collections.nCopies(secondsIntoYear, secondsIntoYear * secondsIntoYear));
    case DBR_WAVEFORM_DOUBLE:
        // Varying number of copies of a typical value
        return new VectorValue<Double>(
                Collections.nCopies(secondsIntoYear, Math.sin(secondsIntoYear * Math.PI / 3600)));
    case DBR_V4_GENERIC_BYTES:
        // Varying number of copies of a typical value
        ByteBuffer buf = ByteBuffer.allocate(1024 * 10);
        buf.put(Integer.toString(secondsIntoYear).getBytes());
        buf.flip();
        return new ByteBufSampleValue(buf);
    default:
        throw new RuntimeException("We seemed to have missed a DBR type when generating sample data");
    }
}

From source file:DiningPhilosophers.java

public Dimension createPhilosophersAndChopsticks() {
    double x, y;//  w  ww.j a  va 2 s .co m
    double radius = 80.0;
    double centerAdj = 85.0;
    double radians;

    Dimension preferredSize = new Dimension(0, 0);

    /*
     * for a straight line y = MARGIN;
     */
    for (int i = 0; i < NUMPHILS; i++)
        chopsticks[i] = new Chopstick();

    for (int i = 0; i < NUMPHILS; i++) {
        /*
         * for a straight line x = i * spacing;
         */
        radians = i * (2.0 * Math.PI / (double) NUMPHILS);
        x = Math.sin(radians) * radius + centerAdj;
        y = Math.cos(radians) * radius + centerAdj;
        philosophers[i] = new Philosopher(this, i, imgs[HUNGRYDUKE]);
        philosophers[i].setBounds((int) x, (int) y, width, height);
        philosopherArea.add(philosophers[i]);
        if ((int) x > preferredSize.width)
            preferredSize.width = (int) x;
        if ((int) y > preferredSize.height)
            preferredSize.height = (int) y;
    }

    preferredSize.width += width;
    preferredSize.height += height;
    return preferredSize;
}

From source file:com.google.publicalerts.cap.validator.MapVisualizer.java

/**
 * Computes the end point of an arc of a great circle given a starting point
 * and arc length.//from ww  w . j a v  a 2 s. co  m
 * See http://williams.best.vwh.net/avform.htm#LL
 *
 * @param heading the direction of the arc, in radians
 * @param arcLength the length of the arc, in kilometers
 * @param latitude latitude of the starting point of the arc
 * @param longitude longitude of the starting point of the arc
 * @return the end point
 */
private JSONArray getRadialEndpoint(double heading, double arcLength, double latitude, double longitude)
        throws JSONException {
    // the angle of the great circle arc
    double earthAngle = arcLength / EARTH_RADIUS_KM;
    // convert decimal degrees to radians for the calculation
    double lat = latitude * DEG_TO_RAD;
    double lng = Math.abs(longitude) * DEG_TO_RAD;
    double asinArg = Math.sin(lat) * Math.cos(earthAngle)
            + Math.cos(lat) * Math.sin(earthAngle) * Math.cos(heading);

    double destLat = Math.asin(asinArg);
    double y = Math.sin(heading) * Math.sin(earthAngle) * Math.cos(lat);
    double x = Math.cos(earthAngle) - Math.sin(lat) * Math.sin(destLat);
    double destLng = (lng - Math.atan2(y, x) + Math.PI) % (2 * Math.PI) - Math.PI;

    return toJsPoint(destLat * RAD_TO_DEG, destLng * RAD_TO_DEG * (longitude < 0 ? -1 : 1));
}

From source file:SWT2D.java

private void run() {
    // Create top level shell
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Java 2D Example");
    // GridLayout for canvas and button
    shell.setLayout(new GridLayout());
    // Create container for AWT canvas
    final Composite canvasComp = new Composite(shell, SWT.EMBEDDED);
    // Set preferred size
    GridData data = new GridData();
    data.widthHint = 600;/*from w w w. j  ava  2s  .c o  m*/
    data.heightHint = 500;
    canvasComp.setLayoutData(data);
    // Create AWT Frame for Canvas
    java.awt.Frame canvasFrame = SWT_AWT.new_Frame(canvasComp);
    // Create Canvas and add it to the Frame
    final java.awt.Canvas canvas = new java.awt.Canvas();
    canvasFrame.add(canvas);
    // Get graphical context and cast to Java2D
    final java.awt.Graphics2D g2d = (java.awt.Graphics2D) canvas.getGraphics();
    // Enable antialiasing
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    // Remember initial transform
    final java.awt.geom.AffineTransform origTransform = g2d.getTransform();
    // Create Clear button and position it
    Button clearButton = new Button(shell, SWT.PUSH);
    clearButton.setText("Clear");
    data = new GridData();
    data.horizontalAlignment = GridData.CENTER;
    clearButton.setLayoutData(data);
    // Event processing for Clear button
    clearButton.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            // Delete word list and redraw canvas
            wordList.clear();
            canvasComp.redraw();
        }
    });
    // Process canvas mouse clicks
    canvas.addMouseListener(new java.awt.event.MouseListener() {
        public void mouseClicked(java.awt.event.MouseEvent e) {
        }

        public void mouseEntered(java.awt.event.MouseEvent e) {
        }

        public void mouseExited(java.awt.event.MouseEvent e) {
        }

        public void mousePressed(java.awt.event.MouseEvent e) {
            // Manage pop-up editor
            display.syncExec(new Runnable() {
                public void run() {
                    if (eShell == null) {
                        // Create new Shell: non-modal!
                        eShell = new Shell(shell, SWT.NO_TRIM | SWT.MODELESS);
                        eShell.setLayout(new FillLayout());
                        // Text input field
                        eText = new Text(eShell, SWT.BORDER);
                        eText.setText("Text rotation in the SWT?");
                        eShell.pack();
                        // Set position (Display coordinates)
                        java.awt.Rectangle bounds = canvas.getBounds();
                        org.eclipse.swt.graphics.Point pos = canvasComp.toDisplay(bounds.width / 2,
                                bounds.height / 2);
                        Point size = eShell.getSize();
                        eShell.setBounds(pos.x, pos.y, size.x, size.y);
                        // Open Shell
                        eShell.open();
                    } else if (!eShell.isVisible()) {
                        // Editor versteckt, sichtbar machen
                        eShell.setVisible(true);
                    } else {
                        // Editor is visible - get text
                        String t = eText.getText();
                        // set editor invisible
                        eShell.setVisible(false);
                        // Add text to list and redraw canvas
                        wordList.add(t);
                        canvasComp.redraw();
                    }
                }
            });
        }

        public void mouseReleased(java.awt.event.MouseEvent e) {
        }
    });
    // Redraw the canvas
    canvasComp.addPaintListener(new PaintListener() {
        public void paintControl(PaintEvent e) {
            // Pass the redraw task to AWT event queue
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    // Compute canvas center
                    java.awt.Rectangle bounds = canvas.getBounds();
                    int originX = bounds.width / 2;
                    int originY = bounds.height / 2;
                    // Reset canvas
                    g2d.setTransform(origTransform);
                    g2d.setColor(java.awt.Color.WHITE);
                    g2d.fillRect(0, 0, bounds.width, bounds.height);
                    // Set font
                    g2d.setFont(new java.awt.Font("Myriad", java.awt.Font.PLAIN, 32));
                    double angle = 0d;
                    // Prepare star shape
                    double increment = Math.toRadians(30);
                    Iterator iter = wordList.iterator();
                    while (iter.hasNext()) {
                        // Determine text colors in RGB color cycle
                        float red = (float) (0.5 + 0.5 * Math.sin(angle));
                        float green = (float) (0.5 + 0.5 * Math.sin(angle + Math.toRadians(120)));
                        float blue = (float) (0.5 + 0.5 * Math.sin(angle + Math.toRadians(240)));
                        g2d.setColor(new java.awt.Color(red, green, blue));
                        // Redraw text
                        String text = (String) iter.next();
                        g2d.drawString(text, originX + 50, originY);
                        // Rotate for next text output
                        g2d.rotate(increment, originX, originY);
                        angle += increment;
                    }
                }
            });
        }
    });
    // Finish shell and open it
    shell.pack();
    shell.open();
    // SWT event processing
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:edu.ucsf.valelab.saim.calculations.SaimFunction.java

/**
 * Calculates the derivative of the SAIM function with respect to A, B, and h
 * at a given angle/*from   w  w  w  . j a  v  a 2  s . c  o  m*/
 * 
 * @param x - angle in radians
 * @param parameters - array of 3 values:
 *    A - scaling parameter
 *    B - offset parameter, accounting for background
 *    h - height in nm
 * @return - array of 3 values with the partial derivatives for A, B, and h
 */
@Override
public double[] gradient(double x, double... parameters) {
    if (parameters.length != 3)
        throw new DimensionMismatchException(parameters.length, 3);

    angle_ = x;
    double A = parameters[0];
    double h = parameters[2];

    // partial derivative for A is the square of |1+rTE*eiphi(h)|
    Complex rTE = getFresnelTE(angle_);
    double f = 4.0 * Math.PI * sd_.nSample_ * Math.cos(angle_) / sd_.wavelength_;
    double phaseDiff = f * h;
    double c = rTE.getReal();
    double d = rTE.getImaginary();
    double val = 1 + 2 * c * Math.cos(phaseDiff) - 2 * d * Math.sin(phaseDiff) + c * c + d * d;

    // partial derivative for B is 1 or angle
    double bDerivative = 1.0;
    if (sd_.useBAngle_)
        bDerivative = angle_;

    // partial derivate for h is 
    //     - 2*A*c*f*sin(fh) - 2*A*d*f*cos(fh)
    // where f = phaseDiffFactor
    // c = rTE.Real(), and d = rTE.Imaginary()

    double pdh = -2 * A * f * (c * Math.sin(phaseDiff) + d * Math.cos(phaseDiff));

    double result[] = { val, bDerivative, pdh };
    return result;
}

From source file:edu.ku.brc.ui.GraphicsUtils.java

/**
 * Returns the value of <code>len * Math.sin(dir)</code>.
 * Code stolen from http://forum.java.sun.com/thread.jspa?threadID=378460&tstart=135.
 *
 * @param len the length//from w  ww  .  j  ava  2 s. c om
 * @param dir the angle in radians
 * @return the result
 */
private static int xCor(int len, double dir) {
    return (int) (len * Math.sin(dir));
}

From source file:com.sk89q.craftbook.sponge.mechanics.BounceBlocks.java

private void doAction(Entity entity, String positionString, Vector3d rotation) {
    if (entity instanceof Player) {
        if (!usePermissions.hasPermission((Subject) entity)) {
            return;
        }/*from ww w .  j a v a 2  s  .co m*/
    }

    double x = 0;
    double y;
    double z = 0;
    boolean straight = positionString.startsWith("!");

    String[] bits = RegexUtil.COMMA_PATTERN.split(StringUtils.replace(positionString, "!", ""));
    if (bits.length == 0) {
        y = 0.5;
    } else if (bits.length == 1) {
        try {
            y = Double.parseDouble(bits[0]);
        } catch (NumberFormatException e) {
            y = 0.5;
        }
    } else {
        x = Double.parseDouble(bits[0]);
        y = Double.parseDouble(bits[1]);
        z = Double.parseDouble(bits[2]);
    }

    if (!straight) {
        double pitch = ((rotation.getX() + 90d) * Math.PI) / 180d;
        double yaw = ((rotation.getY() + 90d) * Math.PI) / 180d;

        x *= Math.sin(pitch) * Math.cos(yaw);
        z *= Math.sin(pitch) * Math.sin(yaw);
    }

    entity.setVelocity(new Vector3d(x, y, z));
    entity.offer(Keys.FALL_DISTANCE, -20f);
}

From source file:msi.gama.common.geometry.Rotation3D.java

/**
 * By default around the Z axis (PLUS_K)
 * /*from   w  ww .  j  a  v  a2 s  .  c o m*/
 * @param angle
 *            rotation angle in radians
 */
public Rotation3D(final double angle) {
    final double halfAngle = -0.5 * angle;
    q0 = Math.cos(halfAngle);
    q1 = 0;
    q2 = 0;
    q3 = Math.sin(halfAngle);
}

From source file:imagingbook.pub.fd.FourierDescriptor.java

/**
 * Reconstructs a single spatial point from this FD using
 * coefficients [mm,...,mp] = [m-,...,m+] at the fractional path position t in [0,1].
 *///from w  ww  .  j  av  a  2s.  com
private Complex getReconstructionPoint(double t, int mm, int mp) {
    double x = G[0].re;
    double y = G[0].im;
    for (int m = mm; m <= mp; m++) {
        if (m != 0) {
            Complex Gm = getCoefficient(m);
            double A = reconstructionScale * Gm.re;
            double B = reconstructionScale * Gm.im;
            double phi = 2 * Math.PI * m * t;
            double sinPhi = Math.sin(phi);
            double cosPhi = Math.cos(phi);
            x = x + A * cosPhi - B * sinPhi;
            y = y + A * sinPhi + B * cosPhi;
        }
    }
    return new Complex(x, y);
}

From source file:au.com.rsutton.rosjava.differentialDrive.DiffTf.java

@Override
public void onStart(ConnectedNode connectedNode) {
    // log = connectedNode.getLog();

    final Publisher<Odometry> odomPub = Topic.ODOM.newPublisher(connectedNode, nameSpace);

    final Publisher<TransformStamped> odomBroadcaster = Topic.TF.newPublisher(connectedNode, nameSpace);

    // This CancellableLoop will be canceled automatically when the node
    // shuts/*from ww  w  . ja v a  2  s.  com*/
    // down.
    connectedNode.executeCancellableLoop(new CancellableLoop() {

        @Override
        protected void setup() {
        }

        @Override
        protected void loop() throws InterruptedException {
            update();
            Thread.sleep(rate);
        }

        private void update() {
            long now = System.currentTimeMillis();
            if (now > t_next) {
                long elapsed = now - then;
                then = now;
                elapsed /= 1000;

                // calculate odometry

                double d_left = 0;
                double d_right = 0;
                if (enc_left != null)

                {
                    d_left = (left - enc_left) / ticks_meter;
                    d_right = (right - enc_right) / ticks_meter;
                }
                enc_left = left;
                enc_right = right;

                // distance traveled is the average of the two wheels
                double d = (d_left + d_right) / 2;
                // this approximation works (in radians) for small angles
                th = (d_right - d_left) / base_width;
                // calculate velocities
                dx = d / elapsed;
                dr = th / elapsed;

                if (d != 0) {
                    // calculate distance traveled in x and y
                    x = Math.cos(th) * d;
                    y = -Math.sin(th) * d;
                    // calculate the final position of the robot
                    x = x + (Math.cos(th) * x - Math.sin(th) * y);
                    y = y + (Math.sin(th) * x + Math.cos(th) * y);
                }
                if (th != 0) {
                    th = th + th;
                }

                // publish the odom information
                TransformStamped transform = odomBroadcaster.newMessage();
                transform.getTransform().getRotation().setX(0);
                transform.getTransform().getRotation().setY(0);
                transform.getTransform().getRotation().setZ(Math.sin(th / 2));
                transform.getTransform().getRotation().setW(Math.cos(th / 2));
                transform.getTransform().getTranslation().setX(x);
                transform.getTransform().getTranslation().setY(y);
                transform.getTransform().getTranslation().setZ(0);
                transform.getHeader().setStamp(new Time());
                transform.setChildFrameId(odom_frame_id);
                transform.getHeader().setFrameId(base_frame_id);
                odomBroadcaster.publish(transform);

                Odometry odom = odomPub.newMessage();

                odom.getHeader().setStamp(new Time());
                odom.getHeader().setFrameId(odom_frame_id);
                odom.getPose().getPose().getPosition().setX(x);
                odom.getPose().getPose().getPosition().setY(y);
                odom.getPose().getPose().getPosition().setZ(0);
                odom.getPose().getPose().setOrientation(transform.getTransform().getRotation());
                odom.setChildFrameId(base_frame_id);
                odom.getTwist().getTwist().getLinear().setX(dx);
                odom.getTwist().getTwist().getLinear().setY(0);
                odom.getTwist().getTwist().getAngular().setZ(dr);
                odomPub.publish(odom);

            }
        }
    });

    Subscriber<Int16> sub_lwheel = Topic.LWHEEL.newSubscriber(connectedNode, nameSpace);
    sub_lwheel.addMessageListener(new MessageListener<Int16>() {
        @Override
        public void onNewMessage(Int16 message) {
            short enc = message.getData();
            if (enc < encoder_low_wrap && prev_lencoder > encoder_high_wrap) {
                lmult = lmult + 1;
            }

            if (enc > encoder_high_wrap && prev_lencoder < encoder_low_wrap) {
                lmult = lmult - 1;
            }

            left = 1.0 * (enc + lmult * (encoder_max - encoder_min));
            prev_lencoder = enc;
        }
    });
    Subscriber<Int16> sub_rwheel = Topic.RWHEEL.newSubscriber(connectedNode, nameSpace);
    sub_rwheel.addMessageListener(new MessageListener<Int16>() {
        @Override
        public void onNewMessage(Int16 message) {
            short enc = message.getData();
            if (enc < encoder_low_wrap && prev_rencoder > encoder_high_wrap) {
                rmult = rmult + 1;
            }

            if (enc > encoder_high_wrap && prev_rencoder < encoder_low_wrap) {
                rmult = rmult - 1;
            }

            right = 1.0 * (enc + rmult * (encoder_max - encoder_min));
            prev_rencoder = enc;
        }
    });

}