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:Main.java

public static void main(String[] args) {
    JFrame frame = new JFrame();
    DrawPanel dp = new DrawPanel();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(dp);/*  w w w  .j a  va 2  s .c  om*/
    frame.pack();
    frame.setLocationByPlatform(true);
    try {
        Sequence seq = new Sequence(Sequence.PPQ, 4);
        Track track = seq.createTrack();
        for (int i = 0; i < 120; i += 4) {
            int d = (int) Math.abs(new Random().nextGaussian() * 24) + 32;
            track.add(makeEvent(ShortMessage.NOTE_ON, 1, d, 127, i));
            track.add(makeEvent(ShortMessage.CONTROL_CHANGE, 1, 127, 0, i));
            track.add(makeEvent(ShortMessage.NOTE_OFF, 1, d, 127, i));
        }
        Sequencer sequencer = MidiSystem.getSequencer();
        sequencer.open();
        sequencer.setSequence(seq);
        sequencer.addControllerEventListener(dp, new int[] { 127 });
        sequencer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
    frame.setVisible(true);
}

From source file:Snippet31.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setSize(200, 200);/*from  w ww  . j a v a 2 s .  co m*/
    shell.open();
    Listener listener = new Listener() {
        Point point = null;

        static final int JITTER = 8;

        public void handleEvent(Event event) {
            switch (event.type) {
            case SWT.MouseDown:
                point = new Point(event.x, event.y);
                break;
            case SWT.MouseMove:
                if (point == null)
                    return;
                int deltaX = point.x - event.x, deltaY = point.y - event.y;
                if (Math.abs(deltaX) < JITTER && Math.abs(deltaY) < JITTER) {
                    return;
                }
                Tracker tracker = new Tracker(display, SWT.NONE);
                Rectangle rect = display.map(shell, null, shell.getClientArea());
                rect.x -= deltaX;
                rect.y -= deltaY;
                tracker.setRectangles(new Rectangle[] { rect });
                tracker.open();
                // FALL THROUGH
            case SWT.MouseUp:
                point = null;
                break;
            }
        }
    };
    shell.addListener(SWT.MouseDown, listener);
    shell.addListener(SWT.MouseMove, listener);
    shell.addListener(SWT.MouseUp, listener);
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:mase.deprecated.FastMathTest.java

public static void main(String[] args) {
    double MIN = -10;
    double MAX = 10;
    int N = 10000;
    DescriptiveStatistics diff = new DescriptiveStatistics();
    DescriptiveStatistics diffJava = new DescriptiveStatistics();
    long tFast = 0, tNormal = 0, tBounded = 0, tJava = 0;
    for (int i = 0; i < N; i++) {
        double x = Math.random() * (MAX - MIN) + MIN;
        long t = System.nanoTime();
        double v1 = (1.0 / (1.0 + FastMath.expQuick(-1 * x)));
        tFast += System.nanoTime() - t;
        t = System.nanoTime();/*from www. j a  va 2 s.com*/
        double v2 = (1.0 / (1.0 + FastMath.exp(-1 * x)));
        tNormal += System.nanoTime() - t;
        t = System.nanoTime();
        double v3 = (1.0 / (1.0 + BoundMath.exp(-1 * x)));
        tBounded += System.nanoTime() - t;
        t = System.nanoTime();
        double v4 = (1.0 / (1.0 + Math.exp(-1 * x)));
        tJava += System.nanoTime() - t;
        diff.addValue(Math.abs(v1 - v2));
        diffJava.addValue(Math.abs(v3 - v1));
    }

    System.out.println("MAX: " + diff.getMax());
    System.out.println("MEAN: " + diff.getMean());
    System.out.println("MAX JAVA: " + diffJava.getMax());
    System.out.println("MEAN JAVA: " + diffJava.getMean());

    System.out.println("Fast: " + tFast);
    System.out.println("Normal: " + tNormal);
    System.out.println("Bounded: " + tBounded);
    System.out.println("Java: " + tJava);
}

From source file:com.welty.novello.coca.RandGameMvSource.java

/**
 * Select s8rXX, non-anti, games from the file  ~/dev/novello/Othello/latest.223270.bz2
 *///from w  w  w.  j av a  2  s  .  com
public static void main(String[] args) throws IOException, CompressorException {
    final List<MeValue> mvs = new RandGameMvSource().getMvs();
    System.out.format("%,d total positions", mvs.size());

    int nPrinted = 0;
    for (MeValue mv : mvs) {
        if (Math.abs(mv.value) > 2000 && mv.nEmpty() < 3) {
            System.out.println(mv);
            nPrinted++;
        }
        if (nPrinted > 100) {
            break;
        }
    }
}

From source file:org.eclipse.swt.snippets.Snippet273.java

public static void main(String[] args) {
    final String[] MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
            "Dec" };
    final int[] HIGHS = { -7, -4, 1, 11, 18, 24, 26, 25, 20, 13, 5, -4 };
    final int[] LOWS = { -15, -13, -7, 1, 7, 13, 15, 14, 10, 4, -2, -11 };
    final int SCALE_MIN = -30;
    final int SCALE_MAX = 30;
    final int SCALE_RANGE = Math.abs(SCALE_MIN - SCALE_MAX);

    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 273");
    shell.setBounds(10, 10, 400, 350);/*from   w w w. j  a va 2s.  c o  m*/
    shell.setText("Ottawa Average Daily Temperature Ranges");
    final Color blue = display.getSystemColor(SWT.COLOR_BLUE);
    final Color white = display.getSystemColor(SWT.COLOR_WHITE);
    final Color red = display.getSystemColor(SWT.COLOR_RED);
    // final Image parliamentImage = new Image(display, "./parliament.jpg");
    final Table table = new Table(shell, SWT.NONE);
    table.setBounds(10, 10, 350, 300);
    // table.setBackgroundImage(parliamentImage);
    for (int i = 0; i < 12; i++) {
        TableItem item = new TableItem(table, SWT.NONE);
        item.setText(MONTHS[i] + " (" + LOWS[i] + "C..." + HIGHS[i] + "C)");
    }
    final int clientWidth = table.getClientArea().width;

    /*
     * NOTE: MeasureItem and EraseItem are called repeatedly. Therefore it is
     * critical for performance that these methods be as efficient as possible.
     */
    table.addListener(SWT.MeasureItem, event -> {
        int itemIndex = table.indexOf((TableItem) event.item);
        int rightX = (HIGHS[itemIndex] - SCALE_MIN) * clientWidth / SCALE_RANGE;
        event.width = rightX;
    });
    table.addListener(SWT.EraseItem, event -> {
        int itemIndex = table.indexOf((TableItem) event.item);
        int leftX = (LOWS[itemIndex] - SCALE_MIN) * clientWidth / SCALE_RANGE;
        int rightX = (HIGHS[itemIndex] - SCALE_MIN) * clientWidth / SCALE_RANGE;
        GC gc = event.gc;
        Rectangle clipping = gc.getClipping();
        clipping.x = leftX;
        clipping.width = rightX - leftX;
        gc.setClipping(clipping);
        Color oldForeground = gc.getForeground();
        Color oldBackground = gc.getBackground();
        gc.setForeground(blue);
        gc.setBackground(white);
        gc.fillGradientRectangle(event.x, event.y, event.width / 2, event.height, false);
        gc.setForeground(white);
        gc.setBackground(red);
        gc.fillGradientRectangle(event.x + event.width / 2, event.y, event.width / 2, event.height, false);
        gc.setForeground(oldForeground);
        gc.setBackground(oldBackground);
        event.detail &= ~SWT.BACKGROUND;
        event.detail &= ~SWT.HOT;
    });

    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    // parliamentImage.dispose();
    display.dispose();
}

From source file:org.eclipse.swt.snippets.Snippet31.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Snippet 31");
    shell.setSize(200, 200);/*from w w w  . j  av a  2s.c  o m*/
    shell.open();
    Listener listener = new Listener() {
        Point point = null;
        static final int JITTER = 8;

        @Override
        public void handleEvent(Event event) {
            switch (event.type) {
            case SWT.MouseDown:
                point = new Point(event.x, event.y);
                break;
            case SWT.MouseMove:
                if (point == null)
                    return;
                int deltaX = point.x - event.x, deltaY = point.y - event.y;
                if (Math.abs(deltaX) < JITTER && Math.abs(deltaY) < JITTER) {
                    return;
                }
                tracker = new Tracker(display, SWT.NONE);
                Rectangle rect = display.map(shell, null, shell.getClientArea());
                rect.x -= deltaX;
                rect.y -= deltaY;
                tracker.setRectangles(new Rectangle[] { rect });
                tracker.open();
                //FALL THROUGH
            case SWT.MouseUp:
                point = null;
                if (tracker != null) {
                    tracker.dispose();
                    tracker = null;
                }
                break;
            }
        }
    };
    shell.addListener(SWT.MouseDown, listener);
    shell.addListener(SWT.MouseMove, listener);
    shell.addListener(SWT.MouseUp, listener);
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:BasicMathDemo.java

public static void main(String[] args) {
    double aNumber = -191.635;

    System.out.println("The absolute value of " + aNumber + " is " + Math.abs(aNumber));
    System.out.println("The ceiling of " + aNumber + " is " + Math.ceil(aNumber));
    System.out.println("The floor of " + aNumber + " is " + Math.floor(aNumber));
    System.out.println("The rint of " + aNumber + " is " + Math.rint(aNumber));
}

From source file:com.super_bits.modulos.paginas.adminTools.PgAdminContainerObjetoTest.java

public static void main(String[] paramentros) {

    // Ask for user input
    System.out.print("Enter 1st value:");

    // use scanner to read the console input
    Scanner scan = new Scanner(System.in);
    String valor = scan.next();/*from  www .  j a  v  a  2s.co m*/
    double valorAtualizado = Double.parseDouble(valor) * 8.333;
    double calculoMultiplo = 10 * (Math.ceil(Math.abs(valorAtualizado / 10)));

    System.out.println(calculoMultiplo);

    double teste = (double) Math.round(Double.parseDouble(valor) * 8.3d) * 10 / 10d;
    System.out.println("TEste:" + teste);

    System.out.println("Result of the operation is " + valor);

    System.out.println(Precision.round(0.912385, 0, BigDecimal.ROUND_HALF_UP));
    int yourScale = 10;
    System.out.println(BigDecimal.valueOf(0.42344534534553453453 - 0.42324534524553453453).setScale(yourScale,
            BigDecimal.ROUND_HALF_UP));
}

From source file:edu.cmu.cs.lti.ark.fn.identification.training.ConvertAlphabetFile.java

public static void main(String[] args) throws Exception {
    final String alphabetFile = args[0];
    final String modelFile = args[1];
    final String outFile = args[2];
    final String featureType = args[3];
    final double threshold = args.length >= 5 ? Double.parseDouble(args[4].trim()) : DEFAULT_THRESHOLD;

    // read in map from feature id -> feature name
    final BiMap<Integer, String> featureNameById = readAlphabetFile(new File(alphabetFile)).inverse();
    // read in parameter values
    final double[] parameters = TrainBatch.loadModel(modelFile);
    // write out list of (feature name, feature value) pairs
    final BufferedWriter output = Files.newWriter(new File(outFile), Charsets.UTF_8);
    try {/*from  ww  w.  j av  a  2  s  . c  o m*/
        output.write(String.format("%s\n", featureType));
        for (int i : xrange(parameters.length)) {
            final double val = parameters[i];
            if (Math.abs(val) <= threshold)
                continue;
            output.write(String.format("%s\t%s\n", featureNameById.get(i), val));
        }
    } finally {
        closeQuietly(output);
    }
}

From source file:net.liuxuan.temp.filterTest.java

public static void main(String[] args) {
    double constantVoltage = 10d;
    double measurementNoise = 0.1d;
    double processNoise = 1e-5d;

    // A = [ 1 ]/*from  w  w w .j a  v  a 2s. co  m*/
    RealMatrix A = new Array2DRowRealMatrix(new double[] { 1d });
    // B = null
    RealMatrix B = null;
    // H = [ 1 ]
    RealMatrix H = new Array2DRowRealMatrix(new double[] { 1d });
    // x = [ 10 ]
    RealVector x = new ArrayRealVector(new double[] { constantVoltage });
    // Q = [ 1e-5 ]
    RealMatrix Q = new Array2DRowRealMatrix(new double[] { processNoise });
    // P = [ 1 ]
    RealMatrix P0 = new Array2DRowRealMatrix(new double[] { 1d });
    // R = [ 0.1 ]
    RealMatrix R = new Array2DRowRealMatrix(new double[] { measurementNoise });

    ProcessModel pm = new DefaultProcessModel(A, B, Q, x, P0);
    MeasurementModel mm = new DefaultMeasurementModel(H, R);
    KalmanFilter filter = new KalmanFilter(pm, mm);

    // process and measurement noise vectors
    RealVector pNoise = new ArrayRealVector(1);
    RealVector mNoise = new ArrayRealVector(1);

    RandomGenerator rand = new JDKRandomGenerator();
    // iterate 60 steps
    for (int i = 0; i < 60; i++) {
        filter.predict();

        // simulate the process
        //            pNoise.setEntry(0, processNoise * rand.nextGaussian());
        pNoise.setEntry(0, Math.sin(Math.PI * 2 * i / 6));
        //            System.out.println("============");
        //            System.out.println(Math.sin(Math.PI*2*i/6));

        // x = A * x + p_noise
        x = A.operate(x).add(pNoise);
        // simulate the measurement
        //            mNoise.setEntry(0, measurementNoise * rand.nextGaussian());
        mNoise.setEntry(0, 0);

        // z = H * x + m_noise
        RealVector z = H.operate(x).add(mNoise);
        filter.correct(z);

        double voltage = filter.getStateEstimation()[0];
        System.out.println(voltage);

        // state estimate shouldn't be larger than the measurement noise
        double diff = Math.abs(x.getEntry(0) - filter.getStateEstimation()[0]);
        System.out.println("diff = " + diff);

    }
}