Example usage for java.lang Math abs

List of usage examples for java.lang Math abs

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public static double abs(double a) 

Source Link

Document

Returns the absolute value of a double value.

Usage

From source file:MouseWheelTest.java

public MouseWheelTest() {
    super();/*from  w  w w  .jav  a 2  s.  com*/
    final Container contentPane = getContentPane();

    MouseWheelListener listener = new MouseWheelListener() {
        int colorCounter;

        private static final int UP = 1;

        private static final int DOWN = 2;

        public void mouseWheelMoved(MouseWheelEvent e) {
            int count = e.getWheelRotation();
            int direction = (Math.abs(count) > 0) ? UP : DOWN;
            changeBackground(direction);
        }

        private void changeBackground(int direction) {
            contentPane.setBackground(colors[colorCounter]);

            if (direction == UP) {
                colorCounter++;
            } else {
                --colorCounter;
            }

            if (colorCounter == colors.length) {
                colorCounter = 0;
            } else if (colorCounter < 0) {
                colorCounter = colors.length - 1;
            }
        }
    };
    contentPane.addMouseWheelListener(listener);
}

From source file:org.traccar.WebDataHandler.java

private static String formatSentence(Position position) {

    StringBuilder s = new StringBuilder("$GPRMC,");

    try (Formatter f = new Formatter(s, Locale.ENGLISH)) {

        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ENGLISH);
        calendar.setTimeInMillis(position.getFixTime().getTime());

        f.format("%1$tH%1$tM%1$tS.%1$tL,A,", calendar);

        double lat = position.getLatitude();
        double lon = position.getLongitude();

        f.format("%02d%07.4f,%c,", (int) Math.abs(lat), Math.abs(lat) % 1 * 60, lat < 0 ? 'S' : 'N');
        f.format("%03d%07.4f,%c,", (int) Math.abs(lon), Math.abs(lon) % 1 * 60, lon < 0 ? 'W' : 'E');

        f.format("%.2f,%.2f,", position.getSpeed(), position.getCourse());
        f.format("%1$td%1$tm%1$ty,,", calendar);
    }//from   w  w  w .  ja  v a 2 s  .  c om

    s.append(Checksum.nmea(s.toString()));

    return s.toString();
}

From source file:StringUtils.java

/**
 * Given an integer, return a string that is in an approximate, but human 
 * readable format. //from   w  ww . jav  a  2s.c o  m
 * It uses the bases 'k', 'm', and 'g' for 1024, 1024**2, and 1024**3.
 * @param number the number to format
 * @return a human readable form of the integer
 */
public static String humanReadableInt(long number) {
    long absNumber = Math.abs(number);
    double result = number;
    String suffix = "";
    if (absNumber < 1024) {
        // nothing
    } else if (absNumber < 1024 * 1024) {
        result = number / 1024.0;
        suffix = "k";
    } else if (absNumber < 1024 * 1024 * 1024) {
        result = number / (1024.0 * 1024);
        suffix = "m";
    } else {
        result = number / (1024.0 * 1024 * 1024);
        suffix = "g";
    }
    return oneDecimal.format(result) + suffix;
}

From source file:Main.java

/**
 * Find the preview size that best fit the prescribed one.
 *///from  w  ww  .  ja  v a 2s. c om
public static Camera.Size getOptimalPreviewSize(Camera.Parameters params, int w, int h) {
    List<Camera.Size> sizes = params.getSupportedPreviewSizes();

    // Use a very small tolerance because we want an exact match.
    final double ASPECT_TOLERANCE = 0.1;
    double targetRatio = (double) w / h;
    if (sizes == null)
        return null;

    Camera.Size optimalSize = null;

    // Start with max value and refine as we iterate over available preview sizes. This is the
    // minimum difference between view and camera height.
    double minDiff = Double.MAX_VALUE;

    // Target view height
    int targetHeight = h;

    // Try to find a preview size that matches aspect ratio and the target view size.
    // Iterate over all available sizes and pick the largest size that can fit in the view and
    // still maintain the aspect ratio.
    for (Camera.Size size : sizes) {
        double ratio = (double) size.width / size.height;
        if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
            continue;
        if (Math.abs(size.height - targetHeight) < minDiff) {
            optimalSize = size;
            minDiff = Math.abs(size.height - targetHeight);
        }
    }

    // Cannot find preview size that matches the aspect ratio, ignore the requirement
    if (optimalSize == null) {
        minDiff = Double.MAX_VALUE;
        for (Camera.Size size : sizes) {
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }
    }

    return optimalSize;
}

From source file:Main.java

/**
 * Convert a color to a HSL array./*from ww w. j  a v  a  2 s  . c  o m*/
 * 
 * @param color The color to convert.
 * @param hsl A size-3 array to load with the HSL values.
 */
public static void colorToHsl(int color, float[] hsl) {
    float r = ((0x00ff0000 & color) >> 16) / 255.0F;
    float g = ((0x0000ff00 & color) >> 8) / 255.0F;
    float b = ((0x000000ff & color)) / 255.0F;
    float max = Math.max(Math.max(r, g), b);
    float min = Math.min(Math.min(r, g), b);
    float c = max - min;

    float hTemp = 0.0F;
    if (c == 0) {
        hTemp = 0;
    } else if (max == r) {
        hTemp = (float) (g - b) / c;
        if (hTemp < 0)
            hTemp += 6.0F;
    } else if (max == g) {
        hTemp = (float) (b - r) / c + 2.0F;
    } else if (max == b) {
        hTemp = (float) (r - g) / c + 4.0F;
    }
    float h = 60.0F * hTemp;

    float l = (max + min) * 0.5F;

    float s;
    if (c == 0) {
        s = 0.0F;
    } else {
        s = c / (1 - Math.abs(2.0F * l - 1.0F));
    }

    hsl[0] = h;
    hsl[1] = s;
    hsl[2] = l;
}

From source file:com.intuit.tank.service.impl.v1.report.FileReader.java

/**
 * Gets a StreamingOutput from the passedin file from start to end or from beginning to end if start is greater than
 * end. if a negative number is passed, it will get the last n lines of the file. If 0 is passed it will return the
 * entire file./*from w w w . j  av  a 2s .co  m*/
 * 
 * @param total
 * 
 * @return a StreamingOutput
 */
public static StreamingOutput getFileStreamingOutput(final File f, long total, String start) {

    long l = 0;
    if (start != null) {
        try {
            l = Long.parseLong(start);
            // num lines to get from end
            if (l < 0) {
                l = getStartChar(f, Math.abs(l), total);
            }
        } catch (Exception e) {
            LOG.error("Error parsing start " + start + ": " + e);
        }
    }
    final long to = l > total ? 0 : total;
    final long from = l;

    StreamingOutput streamer = new StreamingOutput() {
        @SuppressWarnings("resource")
        @Override
        public void write(final OutputStream output) throws IOException, WebApplicationException {

            final FileChannel inputChannel = new FileInputStream(f).getChannel();
            final WritableByteChannel outputChannel = Channels.newChannel(output);
            try {
                inputChannel.transferTo(from, to, outputChannel);
            } finally {
                // closing the channels
                inputChannel.close();
                outputChannel.close();
            }
        }
    };
    LOG.debug("returning data from " + from + " - " + to + " of total " + total);
    return streamer;
}

From source file:com.opengamma.analytics.math.statistics.descriptive.robust.SampleMedianAbsoluteDeviationCalculator.java

@Override
public Double evaluate(final double[] x) {
    Validate.notNull(x, "x");
    final int n = x.length;
    Validate.isTrue(n > 1, "Need at least two data points to calculate MAD");
    final double median = MEDIAN.evaluate(x);
    final double[] diff = new double[n];
    for (int i = 0; i < n; i++) {
        diff[i] = Math.abs(x[i] - median);
    }// ww  w.  ja  va  2 s. com
    return MEDIAN.evaluate(diff);
}

From source file:ResizeRectangle.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D) g;

    for (int i = 0; i < points.length; i++) {
        g2.fill(points[i]);//from  w w  w .j a  v a 2 s .  c  om
    }
    s.setRect(points[0].getCenterX(), points[0].getCenterY(),
            Math.abs(points[1].getCenterX() - points[0].getCenterX()),
            Math.abs(points[1].getCenterY() - points[0].getCenterY()));

    g2.draw(s);
}

From source file:Main.java

/**
 * Convert RGB components to HSL (hue-saturation-lightness).
 * <ul>//  w  w  w  .  j av a 2 s  . c  om
 * <li>hsl[0] is Hue [0 .. 360)</li>
 * <li>hsl[1] is Saturation [0...1]</li>
 * <li>hsl[2] is Lightness [0...1]</li>
 * </ul>
 *
 * @param r   red component value [0..255]
 * @param g   green component value [0..255]
 * @param b   blue component value [0..255]
 * @param hsl 3 element array which holds the resulting HSL components.
 */
public static void RGBToHSL(int r, int g, int b, float[] hsl) {
    final float rf = r / 255f;
    final float gf = g / 255f;
    final float bf = b / 255f;

    final float max = Math.max(rf, Math.max(gf, bf));
    final float min = Math.min(rf, Math.min(gf, bf));
    final float deltaMaxMin = max - min;

    float h, s;
    float l = (max + min) / 2f;

    if (max == min) {
        // Monochromatic
        h = s = 0f;
    } else {
        if (max == rf) {
            h = ((gf - bf) / deltaMaxMin) % 6f;
        } else if (max == gf) {
            h = ((bf - rf) / deltaMaxMin) + 2f;
        } else {
            h = ((rf - gf) / deltaMaxMin) + 4f;
        }

        s = deltaMaxMin / (1f - Math.abs(2f * l - 1f));
    }

    hsl[0] = (h * 60f) % 360f;
    hsl[1] = s;
    hsl[2] = l;
}

From source file:Main.java

/**
 * Find the difference between two bitmaps using average of per-pixel differences.
 *
 * @param a first {@link android.graphics.Bitmap}.
 * @param b second {@link android.graphics.Bitmap}.
 * @return the difference.//from w  w  w.j a  va 2 s.c  o m
 */
public static double calcDifferenceMetric(Bitmap a, Bitmap b) {
    if (a.getWidth() != b.getWidth() || a.getHeight() != b.getHeight()) {
        throw new IllegalArgumentException("Bitmap dimensions for arguments do not match a=" + a.getWidth()
                + "x" + a.getHeight() + ", b=" + b.getWidth() + "x" + b.getHeight());
    }
    // TODO: Optimize this in renderscript to avoid copy.
    int[] aPixels = new int[a.getHeight() * a.getWidth()];
    int[] bPixels = new int[aPixels.length];
    a.getPixels(aPixels, /*offset*/0, /*stride*/a.getWidth(), /*x*/
            0, /*y*/0, a.getWidth(), a.getHeight());
    b.getPixels(bPixels, /*offset*/0, /*stride*/b.getWidth(), /*x*/
            0, /*y*/0, b.getWidth(), b.getHeight());
    double diff = 0;
    for (int i = 0; i < aPixels.length; i++) {
        int aPix = aPixels[i];
        int bPix = bPixels[i];

        diff += Math.abs(Color.red(aPix) - Color.red(bPix)); // red
        diff += Math.abs(Color.green(aPix) - Color.green(bPix)); // green
        diff += Math.abs(Color.blue(aPix) - Color.blue(bPix)); // blue
    }
    diff /= (aPixels.length * 3);
    return diff;
}