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:com.opengamma.maths.lowlevelapi.functions.utilities.Abs.java

public static int[] stateless(int[] v) {
    Validate.notNull(v);//from w  ww.  j a  v a2 s .c  o  m
    final int n = v.length;
    int[] tmp = new int[n];
    for (int i = 0; i < n; i++) {
        tmp[i] = Math.abs(v[i]);
    }
    return tmp;
}

From source file:com.ms.commons.test.tool.UnitTestTools.java

public static Integer nextInt() {
    return Math.abs(RandomUtils.nextInt());
}

From source file:Main.java

/**
 * Function to calculate the distance in meters from dbm rssi values.
 * http://rvmiller.com/2013/05/part-1-wifi-based-trilateration-on-android/
 *
 * The function is based on Free Space Path Loss, and may not work with
 * indoor signal propagation.//from   w w  w . j  ava2  s  . co  m
 *
 * @param levelInDb RSSI value.
 * @param freqInMHz Frequency of the sending device.
 * @return Distance in meters.
 */
public static double distanceFSPL(double levelInDb, double freqInMHz) {
    double exp = (27.55 - (20 * Math.log10(freqInMHz)) + Math.abs(levelInDb)) / 20.0;
    return Math.pow(10.0, exp);
}

From source file:Main.java

/**
 * Calculates distance using Free-space path loss. Constant -27.55 is used for calculations, where frequency is in MHz and distance in meters.
 * FSPL(dB) = 20 log(d) + 20 log(f) - 27.55; d distance from the transmitter [m], f signal frequency [MHz]
 *
 * @param level measured RSSI [dBm]//  w  ww.j a v a  2 s  .  co  m
 * @param freq  WiFi frequency [MHz]
 * @return distance from AP [m]
 */
public static double calculateDistance(double level, double freq) {
    double exp = (27.55 - (20 * Math.log10(freq)) + Math.abs(level)) / 20.0;
    return Math.pow(10.0, exp);
}

From source file:Main.java

public static Camera.Size getOptimalPreviewSizeByAspectRatioAndVideoHeight(List<Camera.Size> sizes,
        double aspectRatio, int maxHeight) {
    if (sizes == null)
        return null;
    Camera.Size optimalSize = null;/*from w w w.j  a  va 2 s . com*/

    // Find size
    for (Camera.Size size : sizes) {
        double ratio = (double) size.width / size.height;
        if (Math.abs(ratio - aspectRatio) > ASPECT_TOLERANCE) {
            continue;
        }
        if (((optimalSize == null) && (size.height <= maxHeight)) || ((optimalSize != null)
                && (optimalSize.height < size.height) && (size.height <= maxHeight))) {
            optimalSize = size;
        }
    }

    return optimalSize;
}

From source file:Main.java

public static boolean withPointRadius(PointF cur, PointF target, float radius) {
    double space_2 = Math.pow(Math.abs(cur.x - target.x), 2) + Math.pow(Math.abs(cur.y - target.y), 2);
    double space = Math.sqrt(space_2);
    if (radius > space) {
        return true;
    }/*from  w  ww. ja  va 2 s.  co  m*/
    return false;
}

From source file:Main.java

public static Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int targetHeight) {
    final double MIN_ASPECT_RATIO = 1.0;
    final double MAX_ASPECT_RATIO = 1.5;
    Camera.Size optimalSize = null;/*from   w w  w.  j  ava 2 s .  c o  m*/
    double minDiff = Double.MAX_VALUE;
    for (Camera.Size size : sizes) {
        double ratio = (double) size.width / size.height;
        if (ratio <= MIN_ASPECT_RATIO || ratio > MAX_ASPECT_RATIO)
            continue;
        if (Math.abs(size.height - targetHeight) < minDiff) {
            optimalSize = size;
            minDiff = Math.abs(size.height - targetHeight);
        }
    }
    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

/**
 * computes the log10 of all values of the passed array
 * @param _arr the array to compute log10 from
 * @return an array containing the log10 of the passed array
 *///from  w  w w  . j a v a  2s.com
public static double[] log10(double[] _arr) {
    double[] res = new double[_arr.length];
    for (int i = 0; i < res.length; i++) {
        if (0.0 == _arr[i]) {
            res[i] = 0;
            continue;
        }
        //         Log.e("ArrayHelper", "before log:"+_arr[i]);
        res[i] = Math.log10(Math.abs(_arr[i]));
        //         Log.e("ArrayHelper", "after log:"+res[i]);
    }
    return res;
}

From source file:Main.java

public static <T> void rotate(Collection<T> collection, int rotateStep) {
    List<T> list = new LinkedList<T>();
    list.addAll(collection);//from   w  w w  . j  a  v  a2s.c  o m
    collection.clear();
    if (rotateStep > 0) {
        if (rotateStep > list.size())
            rotateStep %= list.size();
        collection.addAll(list.subList(list.size() - rotateStep, list.size()));
        collection.addAll(list.subList(0, list.size() - rotateStep));
    } else {
        if (Math.abs(rotateStep) > list.size())
            rotateStep %= list.size();
        rotateStep = Math.abs(rotateStep);
        collection.addAll(list.subList(rotateStep, list.size()));
        collection.addAll(list.subList(0, rotateStep));
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.ExtractDataAndQueryAsSparseVectors.java

public static void main(String[] args) {
    String optKeys[] = { CommonParams.MAX_NUM_QUERY_PARAM, MAX_NUM_DATA_PARAM, CommonParams.MEMINDEX_PARAM,
            IN_QUERIES_PARAM, OUT_QUERIES_PARAM, OUT_DATA_PARAM, TEXT_FIELD_PARAM, TEST_QTY_PARAM, };
    String optDescs[] = { CommonParams.MAX_NUM_QUERY_DESC, MAX_NUM_DATA_DESC, CommonParams.MEMINDEX_DESC,
            IN_QUERIES_DESC, OUT_QUERIES_DESC, OUT_DATA_DESC, TEXT_FIELD_DESC, TEST_QTY_DESC };
    boolean hasArg[] = { true, true, true, true, true, true, true, true };

    ParamHelper prmHlp = null;/*from  w  w w .ja v  a 2  s . c  om*/

    try {

        prmHlp = new ParamHelper(args, optKeys, optDescs, hasArg);

        CommandLine cmd = prmHlp.getCommandLine();
        Options opt = prmHlp.getOptions();

        int maxNumQuery = Integer.MAX_VALUE;

        String tmpn = cmd.getOptionValue(CommonParams.MAX_NUM_QUERY_PARAM);
        if (tmpn != null) {
            try {
                maxNumQuery = Integer.parseInt(tmpn);
            } catch (NumberFormatException e) {
                UsageSpecify(CommonParams.MAX_NUM_QUERY_PARAM, opt);
            }
        }

        int maxNumData = Integer.MAX_VALUE;
        tmpn = cmd.getOptionValue(MAX_NUM_DATA_PARAM);
        if (tmpn != null) {
            try {
                maxNumData = Integer.parseInt(tmpn);
            } catch (NumberFormatException e) {
                UsageSpecify(MAX_NUM_DATA_PARAM, opt);
            }
        }
        String memIndexPref = cmd.getOptionValue(CommonParams.MEMINDEX_PARAM);
        if (null == memIndexPref) {
            UsageSpecify(CommonParams.MEMINDEX_PARAM, opt);
        }
        String textField = cmd.getOptionValue(TEXT_FIELD_PARAM);
        if (null == textField) {
            UsageSpecify(TEXT_FIELD_PARAM, opt);
        }

        textField = textField.toLowerCase();
        int fieldId = -1;
        for (int i = 0; i < FeatureExtractor.mFieldNames.length; ++i)
            if (FeatureExtractor.mFieldNames[i].compareToIgnoreCase(textField) == 0) {
                fieldId = i;
                break;
            }
        if (-1 == fieldId) {
            Usage("Wrong field index, should be one of the following: "
                    + String.join(",", FeatureExtractor.mFieldNames), opt);
        }

        InMemForwardIndex indx = new InMemForwardIndex(
                FeatureExtractor.indexFileName(memIndexPref, FeatureExtractor.mFieldNames[fieldId]));

        BM25SimilarityLucene bm25simil = new BM25SimilarityLucene(FeatureExtractor.BM25_K1,
                FeatureExtractor.BM25_B, indx);

        String inQueryFile = cmd.getOptionValue(IN_QUERIES_PARAM);
        String outQueryFile = cmd.getOptionValue(OUT_QUERIES_PARAM);
        if ((inQueryFile == null) != (outQueryFile == null)) {
            Usage("You should either specify both " + IN_QUERIES_PARAM + " and " + OUT_QUERIES_PARAM
                    + " or none of them", opt);
        }
        String outDataFile = cmd.getOptionValue(OUT_DATA_PARAM);

        tmpn = cmd.getOptionValue(TEST_QTY_PARAM);
        int testQty = 0;
        if (tmpn != null) {
            try {
                testQty = Integer.parseInt(tmpn);
            } catch (NumberFormatException e) {
                UsageSpecify(TEST_QTY_PARAM, opt);
            }
        }

        ArrayList<DocEntry> testDocEntries = new ArrayList<DocEntry>();
        ArrayList<DocEntry> testQueryEntries = new ArrayList<DocEntry>();
        ArrayList<TrulySparseVector> testDocVectors = new ArrayList<TrulySparseVector>();
        ArrayList<TrulySparseVector> testQueryVectors = new ArrayList<TrulySparseVector>();

        if (outDataFile != null) {
            BufferedWriter out = new BufferedWriter(
                    new OutputStreamWriter(CompressUtils.createOutputStream(outDataFile)));

            ArrayList<DocEntryExt> docEntries = indx.getDocEntries();

            for (int id = 0; id < Math.min(maxNumData, docEntries.size()); ++id) {
                DocEntry e = docEntries.get(id).mDocEntry;
                TrulySparseVector v = bm25simil.getDocSparseVector(e, false);
                if (id < testQty) {
                    testDocEntries.add(e);
                    testDocVectors.add(v);
                }
                outputVector(out, v);
            }

            out.close();

        }

        Splitter splitOnSpace = Splitter.on(' ').trimResults().omitEmptyStrings();

        if (outQueryFile != null) {
            BufferedReader inpText = new BufferedReader(
                    new InputStreamReader(CompressUtils.createInputStream(inQueryFile)));
            BufferedWriter out = new BufferedWriter(
                    new OutputStreamWriter(CompressUtils.createOutputStream(outQueryFile)));

            String queryText = XmlHelper.readNextXMLIndexEntry(inpText);

            for (int queryQty = 0; queryText != null && queryQty < maxNumQuery; queryText = XmlHelper
                    .readNextXMLIndexEntry(inpText), queryQty++) {
                Map<String, String> queryFields = null;
                // 1. Parse a query

                try {
                    queryFields = XmlHelper.parseXMLIndexEntry(queryText);
                } catch (Exception e) {
                    System.err.println("Parsing error, offending QUERY:\n" + queryText);
                    throw new Exception("Parsing error.");
                }

                String fieldText = queryFields.get(FeatureExtractor.mFieldsSOLR[fieldId]);

                if (fieldText == null) {
                    fieldText = "";
                }

                ArrayList<String> tmpa = new ArrayList<String>();
                for (String s : splitOnSpace.split(fieldText))
                    tmpa.add(s);

                DocEntry e = indx.createDocEntry(tmpa.toArray(new String[tmpa.size()]));

                TrulySparseVector v = bm25simil.getDocSparseVector(e, true);
                if (queryQty < testQty) {
                    testQueryEntries.add(e);
                    testQueryVectors.add(v);
                }
                outputVector(out, v);
            }

            out.close();
        }

        int testedQty = 0, diffQty = 0;
        // Now let's do some testing
        for (int iq = 0; iq < testQueryEntries.size(); ++iq) {
            DocEntry queryEntry = testQueryEntries.get(iq);
            TrulySparseVector queryVector = testQueryVectors.get(iq);
            for (int id = 0; id < testDocEntries.size(); ++id) {
                DocEntry docEntry = testDocEntries.get(id);
                TrulySparseVector docVector = testDocVectors.get(id);
                float val1 = bm25simil.compute(queryEntry, docEntry);
                float val2 = TrulySparseVector.scalarProduct(queryVector, docVector);
                ++testedQty;
                if (Math.abs(val1 - val2) > 1e5) {
                    System.err.println(
                            String.format("Potential mismatch BM25=%f <-> scalar product=%f", val1, val2));
                    ++diffQty;
                }
            }
        }
        if (testedQty > 0)
            System.out.println(String.format("Tested %d Mismatched %d", testedQty, diffQty));

    } catch (ParseException e) {
        Usage("Cannot parse arguments: " + e, prmHlp != null ? prmHlp.getOptions() : null);
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}