Example usage for java.math BigDecimal round

List of usage examples for java.math BigDecimal round

Introduction

In this page you can find the example usage for java.math BigDecimal round.

Prototype

public BigDecimal round(MathContext mc) 

Source Link

Document

Returns a BigDecimal rounded according to the MathContext settings.

Usage

From source file:org.voltdb.regressionsuites.RegressionSuite.java

protected static final BigDecimal roundDecimalValue(String decimalValueString, boolean roundingEnabled,
        RoundingMode mode) {//from   www .  j  av a  2 s.c o m
    BigDecimal bd = new BigDecimal(decimalValueString);
    if (!roundingEnabled) {
        return bd;
    }
    int precision = bd.precision();
    int scale = bd.scale();
    int lostScale = scale - m_defaultScale;
    if (lostScale <= 0) {
        return bd;
    }
    int newPrecision = precision - lostScale;
    MathContext mc = new MathContext(newPrecision, mode);
    BigDecimal nbd = bd.round(mc);
    assertTrue(nbd.scale() <= m_defaultScale);
    if (nbd.scale() != m_defaultScale) {
        nbd = nbd.setScale(m_defaultScale);
    }
    assertEquals(getRoundingString("Decimal Scale setting failure"), m_defaultScale, nbd.scale());
    return nbd;
}

From source file:com.cecs492a_group4.sp.SingleEvent.java

public synchronized void getYelpSearchResult(final int index1, final String searchToken, final String Address)
        throws InterruptedException {
    Thread thread = new Thread(new Runnable() {
        @Override/*w  w w  .  j a  v  a  2  s .  c o  m*/
        public void run() {
            int randPick = ran.nextInt(limit);
            try {
                String name = "ldkfldsjkfd";
                int full = 0;
                do {

                    randPick = ran.nextInt(limit);
                    System.out.println("Event number : " + index1);
                    System.out.println(randPick);
                    System.out.println("Index: " + randPick);
                    response = yelp.searchByLocation(searchToken, Address, SingleEvent.currentRadius);
                    System.out.println("The current radius : " + SingleEvent.currentRadius);
                    System.out.println(searchToken + " gave me this response: " + response);
                    yp.setResponse(response);
                    // yp.parseBusiness();

                    int nameSIndex = response.indexOf("\"name\"", 1) + 8;

                    for (int i = 0; i < randPick; i++) {
                        nameSIndex = response.indexOf("\"name\"", ++nameSIndex) + 8;
                    }
                    int nameEIndex = response.indexOf("\",", ++nameSIndex);

                    String tmp = response;
                    name = tmp.substring(nameSIndex, nameEIndex);
                    System.out.println(name);
                    full++;
                    if (full >= 4) {
                        full = 0;
                        bussinessNames.clear(); //no more options reset array
                    }
                } while (bussinessNames.contains(name));

                try {
                    bussinessNames.add(index1, name);
                } catch (IndexOutOfBoundsException e) {
                    System.out.println("Array size " + bussinessNames.size());
                    bussinessNames.clear();
                }
                int imgSIndex = response.indexOf("\"image_url\"", 1) + 13;
                int ratingSIndex = response.indexOf("\"rating_img_url\"", 1) + 18;
                int urlSIndex = response.indexOf("\"mobile_url\"", 1) + 14;
                int phoneSIndex = response.indexOf("\"phone\":", 1) + 9;
                int addressSIndex = response.indexOf("\"display_address\"", 1) + 19;
                int distanceSIndex = response.indexOf("\"distance\"", 1) + 12;
                System.out.println("Start index :" + distanceSIndex);
                for (int i = 0; i < randPick; i++) {

                    imgSIndex = response.indexOf("\"image_url\"", ++imgSIndex) + 13;
                    ratingSIndex = response.indexOf("\"rating_img_url\"", ++ratingSIndex) + 18;
                    urlSIndex = response.indexOf("\"mobile_url\"", ++urlSIndex) + 14;
                    phoneSIndex = response.indexOf("\"phone\":", ++phoneSIndex) + 9;
                    addressSIndex = response.indexOf("\"display_address\"", ++addressSIndex) + 19;
                    distanceSIndex = response.indexOf("\"distance\"", ++distanceSIndex) + 12;
                }

                int ratingEIndex = response.indexOf("g\"", ++ratingSIndex) + 1;
                int imgEIndex = response.indexOf("g\"", ++imgSIndex) + 1;
                int phoneEIndex = response.indexOf("\",", ++phoneSIndex);
                int urlEIndex = response.indexOf("rating_img_url", ++urlSIndex) - 4;
                int addressEIndex = response.indexOf("\"], ", ++addressSIndex) + 1;

                //System.out.println("distance = " + response.substring(distanceSIndex,distanceSIndex + 9));
                //String distance = yp.getBusinessDistance(randPick);
                String distance = response.substring(distanceSIndex, distanceSIndex + 9);
                System.out.println("Distance: " + distance);
                double dis;
                try {
                    dis = Double.parseDouble(distance);
                } catch (NumberFormatException e) {
                    dis = 0.0;
                }
                System.out.println("Distance in meters:" + dis);
                System.out.println("Distance in miles:" + meters_to_miles(dis));
                BigDecimal bd = new BigDecimal(meters_to_miles(dis));
                bd = bd.round(new MathContext(2));
                dis = bd.doubleValue();
                System.out.println("dis after conversion " + dis);
                //distance = distance.substring(distanceSIndex,distanceEIndex);

                //activity = yp.getBusinessName(randPick);
                activity = name;
                //rating = yp.getBusinessRating(randPick);
                //I am going to parse the url my self fucking yelp!

                // int imgEIndex = response.indexOf("location",imgSIndex) - 4;
                String phoneNumber = response;
                phoneNumber = phoneNumber.substring(phoneSIndex, phoneEIndex);
                System.out.println("Phone number: " + phoneNumber);
                String tmp2 = response;
                tmp2 = tmp2.substring(imgSIndex, imgEIndex);
                System.out.println("mylink " + tmp2);
                //img_url = yp.getBusinessImageURL(randPick);
                img_url = tmp2;
                System.out.println(img_url);
                //rating_url = yp.getBusinessRatingUrl(randPick);
                String ratingURL = response;
                ratingURL = ratingURL.substring(ratingSIndex, ratingEIndex);
                System.out.println(ratingURL);

                String weburl = response;
                weburl = weburl.substring(urlSIndex, urlEIndex);
                System.out.println("Event URL: " + weburl);

                String eventaddress = response;
                eventaddress = eventaddress.substring(addressSIndex, addressEIndex);

                System.out.println("default Event Address" + eventaddress);

                int streaddSindex = eventaddress.indexOf("\"") + 1;

                int streaddEindex = eventaddress.indexOf("\",");
                int cityaddSindex = 1;
                try {
                    cityaddSindex = eventaddress.indexOf("\", \"") + 4;
                } catch (StringIndexOutOfBoundsException e) {
                    cityaddSindex = 0;
                    System.out.println("No city");
                }

                String streetadd = " ";
                try {
                    streetadd = eventaddress.substring(streaddSindex, streaddEindex);
                } catch (StringIndexOutOfBoundsException e) {
                    if (!Character.isDigit(eventaddress.charAt(0))) {
                        System.out.println("Faulty address");
                        streetadd = " ";
                    }
                }
                System.out.println("Street address:" + streetadd);
                String cityadd;
                if (cityaddSindex != 0)
                    cityadd = eventaddress.substring(cityaddSindex).replace("\"", "");
                else
                    cityadd = " ";

                System.out.println("City location: " + cityadd);
                eventaddress = streetadd + " " + cityadd;
                System.out.println("adjusted Event Address: " + eventaddress);

                //System.out.println(ratingURL);
                event_address = eventaddress;
                phoneNum = phoneNumber;
                web_url = weburl;
                rating_url = ratingURL;
                icon_url = new URL(img_url);
                url_rating = new URL(rating_url);
                try {
                    dayevent.add(index1, new DayEvent(activity, icon_url, url_rating, searchToken, dis, web_url,
                            phoneNum, event_address));
                } catch (IndexOutOfBoundsException e) {
                    System.out.println("Size of day event " + dayevent.size());
                }
                //} catch (JSONException e) {
                //e.printStackTrace();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    });
    thread.start();
    //test by removing the while loops (bad practice)
    /**       while (response == null) {
           }
           while (activity == null) {
           }
           while (web_url == null) {
           }
           while (img_url == null) {
           }
           while (rating_url == null) {
           }**/
    thread.join();

}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The natural logarithm./*  ww w .  j  a  va2s . c  o  m*/
 *
 * @param r  The main argument, a strictly positive value.
 * @param mc The requirements on the precision.
 * @return ln(r).
 */
static public BigDecimal log(final Rational r, final MathContext mc) {
    /* the value is undefined if x is negative.
     */
    if (r.compareTo(Rational.ZERO) <= 0) {
        throw new ArithmeticException("Cannot take log of negative " + r.toString());
    } else if (r.compareTo(Rational.ONE) == 0) {
        return BigDecimal.ZERO;
    } else {
        /* log(r+epsr) = log(r)+epsr/r. Convert the precision to an absolute error in the result.
         * eps contains the required absolute error of the result, epsr/r.
         */
        double eps = prec2err(Math.log(r.doubleValue()), mc.getPrecision());
        /* Convert this further into a requirement of the relative precision in r, given that
         * epsr/r is also the relative precision of r. Add one safety digit.
         */
        MathContext mcloc = new MathContext(1 + err2prec(eps));
        final BigDecimal resul = log(r.BigDecimalValue(mcloc));
        return resul.round(mc);
    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Multiply and round./* w  w  w.j av a2  s. c  o m*/
 *
 * @param x The left factor.
 * @param n The right factor.
 * @return The product x*n.
 */
static public BigDecimal multiplyRound(final BigDecimal x, final int n) {
    BigDecimal resul = x.multiply(new BigDecimal(n));
    /* The estimation of the absolute error in the result is |n*err(x)|
     */
    MathContext mc = new MathContext(n != 0 ? x.precision() : 0);

    return resul.round(mc);

}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Multiply and round.//from w  w  w  .jav a2  s. c  om
 *
 * @param x The left factor.
 * @param n The right factor.
 * @return the product x*n
 */
static public BigDecimal multiplyRound(final BigDecimal x, final BigInteger n) {
    BigDecimal resul = x.multiply(new BigDecimal(n));
    /* The estimation of the absolute error in the result is |n*err(x)|
     */
    MathContext mc = new MathContext(n.compareTo(BigInteger.ZERO) != 0 ? x.precision() : 0);

    return resul.round(mc);

}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The Gamma function.//from  w  w  w .j a va 2s  .co m
 *
 * @param x The argument.
 * @return Gamma(x).
 */
static public BigDecimal Gamma(final BigDecimal x) {
    /* reduce to interval near 1.0 with the functional relation, Abramowitz-Stegun 6.1.33
     */
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return divideRound(Gamma(x.add(BigDecimal.ONE)), x);
    } else if (x.doubleValue() > 1.5) {
        /* Gamma(x) = Gamma(xmin+n) = Gamma(xmin)*Pochhammer(xmin,n).
         */
        int n = (int) (x.doubleValue() - 0.5);
        BigDecimal xmin1 = x.subtract(new BigDecimal(n));

        return multiplyRound(Gamma(xmin1), pochhammer(xmin1, n));

    } else {
        /* apply Abramowitz-Stegun 6.1.33
         */
        BigDecimal z = x.subtract(BigDecimal.ONE);
        /* add intermediately 2 digits to the partial sum accumulation
         */
        z = scalePrec(z, 2);
        MathContext mcloc = new MathContext(z.precision());
        /* measure of the absolute error is the relative error in the first, logarithmic term
         */

        double eps = x.ulp().doubleValue() / x.doubleValue();
        BigDecimal resul = log(scalePrec(x, 2)).negate();

        if (x.compareTo(BigDecimal.ONE) != 0) {
            BigDecimal gammCompl = BigDecimal.ONE.subtract(gamma(mcloc));
            resul = resul.add(multiplyRound(z, gammCompl));

            for (int n = 2;; n++) {
                /* multiplying z^n/n by zeta(n-1) means that the two relative errors add.
                 * so the requirement in the relative error of zeta(n)-1 is that this is somewhat
                 * smaller than the relative error in z^n/n (the absolute error of thelatter is the
                 * absolute error in z)
                 */
                BigDecimal c = divideRound(z.pow(n, mcloc), n);
                MathContext m = new MathContext(err2prec(n * z.ulp().doubleValue() / 2. / z.doubleValue()));
                c = c.round(m);
                /* At larger n, zeta(n)-1 is roughly 1/2^n. The product is c/2^n.
                 * The relative error in c is c.ulp/2/c . The error in the product should be small versus eps/10.
                 * Error from 1/2^n is c*err(sigma-1).
                 * We need a relative error of zeta-1 of the order of c.ulp/50/c. This is an absolute
                 * error in zeta-1 of c.ulp/50/c/2^n, and also the absolute error in zeta, because zeta is
                 * of the order of 1.
                 */

                if (eps / 100. / c.doubleValue() < 0.01) {
                    m = new MathContext(err2prec(eps / 100. / c.doubleValue()));
                } else {
                    m = new MathContext(2);
                }
                /* zeta(n) -1 */
                BigDecimal zetm1 = zeta(n, m).subtract(BigDecimal.ONE);
                c = multiplyRound(c, zetm1);

                if (n % 2 == 0) {
                    resul = resul.add(c);
                } else {
                    resul = resul.subtract(c);
                }
                /* alternating sum, so truncating as eps is reached suffices
                 */

                if (Math.abs(c.doubleValue()) < eps) {
                    break;
                }

            }
        }
        /* The relative error in the result is the absolute error in the
         * input variable times the digamma (psi) value at that point.
         */
        double psi = 0.5772156649;

        double zdbl = z.doubleValue();

        for (int n = 1; n < 5; n++) {
            psi += zdbl / n / (n + zdbl);
        }
        eps = psi * x.ulp().doubleValue() / 2.;
        mcloc = new MathContext(err2prec(eps));

        return exp(resul).round(mcloc);

    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Multiply and round.//w  ww. j a va  2  s. c  om
 *
 * @param x The left factor.
 * @param y The right factor.
 * @return The product x*y.
 */
static public BigDecimal multiplyRound(final BigDecimal x, final BigDecimal y) {
    BigDecimal resul = x.multiply(y);

    /* The estimation of the relative error in the result is the sum of the relative
     * errors |err(y)/y|+|err(x)/x|
     */
    MathContext mc = new MathContext(Math.min(x.precision(), y.precision()));

    return resul.round(mc);

}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Add and round according to the larger of the two ulps.
 *
 * @param x The left summand/*  w w  w . j  a v  a  2  s.co  m*/
 * @param y The right summand
 * @return The sum x+y.
 */
static public BigDecimal addRound(final BigDecimal x, final BigDecimal y) {
    BigDecimal resul = x.add(y);
    /* The estimation of the absolute error in the result is |err(y)|+|err(x)|
     */

    double errR = Math.abs(y.ulp().doubleValue() / 2.) + Math.abs(x.ulp().doubleValue() / 2.);
    MathContext mc = new MathContext(err2prec(resul.doubleValue(), errR));

    return resul.round(mc);

}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The natural logarithm.//from   www. j  a  v a 2 s  .  com
 *
 * @param n  The main argument, a strictly positive integer.
 * @param mc The requirements on the precision.
 * @return ln(n).
 */
static public BigDecimal log(int n, final MathContext mc) {
    /* the value is undefined if x is negative.
     */
    if (n <= 0) {
        throw new ArithmeticException("Cannot take log of negative " + n);
    } else if (n == 1) {
        return BigDecimal.ZERO;
    } else if (n == 2) {
        if (mc.getPrecision() < LOG2.precision()) {
            return LOG2.round(mc);
        } else {
            /* Broadhurst \protect\vrule width0pt\protect\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067}
             * Error propagation: the error in log(2) is twice the error in S(2,-5,...).
             */
            int[] a = { 2, -5, -2, -7, -2, -5, 2, -3 };
            BigDecimal S = broadhurstBBP(2, 1, a, new MathContext(1 + mc.getPrecision()));
            S = S.multiply(new BigDecimal(8));
            S = sqrt(divideRound(S, 3));
            return S.round(mc);
        }
    } else if (n == 3) {
        /* summation of a series roughly proportional to (7/500)^k. Estimate count
         * of terms to estimate the precision (drop the favorable additional
         * 1/k here): 0.013^k <= 10^(-precision), so k*log10(0.013) <= -precision
         * so k>= precision/1.87.
         */
        int kmax = (int) (mc.getPrecision() / 1.87);
        MathContext mcloc = new MathContext(mc.getPrecision() + 1 + (int) (Math.log10(kmax * 0.693 / 1.098)));
        BigDecimal log3 = multiplyRound(log(2, mcloc), 19);
        /* log3 is roughly 1, so absolute and relative error are the same. The
         * result will be divided by 12, so a conservative error is the one
         * already found in mc
         */
        double eps = prec2err(1.098, mc.getPrecision()) / kmax;
        Rational r = new Rational(7153, 524288);
        Rational pk = new Rational(7153, 524288);
        for (int k = 1;; k++) {
            Rational tmp = pk.divide(k);
            if (tmp.doubleValue() < eps) {
                break;
            }
            /* how many digits of tmp do we need in the sum?
             */
            mcloc = new MathContext(err2prec(tmp.doubleValue(), eps));
            BigDecimal c = pk.divide(k).BigDecimalValue(mcloc);
            if (k % 2 != 0) {
                log3 = log3.add(c);
            } else {
                log3 = log3.subtract(c);
            }
            pk = pk.multiply(r);
        }
        log3 = divideRound(log3, 12);
        return log3.round(mc);
    } else if (n == 5) {
        /* summation of a series roughly proportional to (7/160)^k. Estimate count
         * of terms to estimate the precision (drop the favorable additional
         * 1/k here): 0.046^k <= 10^(-precision), so k*log10(0.046) <= -precision
         * so k>= precision/1.33.
         */
        int kmax = (int) (mc.getPrecision() / 1.33);
        MathContext mcloc = new MathContext(mc.getPrecision() + 1 + (int) (Math.log10(kmax * 0.693 / 1.609)));
        BigDecimal log5 = multiplyRound(log(2, mcloc), 14);
        /* log5 is roughly 1.6, so absolute and relative error are the same. The
         * result will be divided by 6, so a conservative error is the one
         * already found in mc
         */
        double eps = prec2err(1.6, mc.getPrecision()) / kmax;
        Rational r = new Rational(759, 16384);
        Rational pk = new Rational(759, 16384);
        for (int k = 1;; k++) {
            Rational tmp = pk.divide(k);
            if (tmp.doubleValue() < eps) {
                break;
            }
            /* how many digits of tmp do we need in the sum?
             */
            mcloc = new MathContext(err2prec(tmp.doubleValue(), eps));
            BigDecimal c = pk.divide(k).BigDecimalValue(mcloc);
            log5 = log5.subtract(c);
            pk = pk.multiply(r);
        }
        log5 = divideRound(log5, 6);
        return log5.round(mc);
    } else if (n == 7) {
        /* summation of a series roughly proportional to (1/8)^k. Estimate count
         * of terms to estimate the precision (drop the favorable additional
         * 1/k here): 0.125^k <= 10^(-precision), so k*log10(0.125) <= -precision
         * so k>= precision/0.903.
         */
        int kmax = (int) (mc.getPrecision() / 0.903);
        MathContext mcloc = new MathContext(
                mc.getPrecision() + 1 + (int) (Math.log10(kmax * 3 * 0.693 / 1.098)));
        BigDecimal log7 = multiplyRound(log(2, mcloc), 3);
        /* log7 is roughly 1.9, so absolute and relative error are the same.
         */
        double eps = prec2err(1.9, mc.getPrecision()) / kmax;
        Rational r = new Rational(1, 8);
        Rational pk = new Rational(1, 8);
        for (int k = 1;; k++) {
            Rational tmp = pk.divide(k);
            if (tmp.doubleValue() < eps) {
                break;
            }
            /* how many digits of tmp do we need in the sum?
             */
            mcloc = new MathContext(err2prec(tmp.doubleValue(), eps));
            BigDecimal c = pk.divide(k).BigDecimalValue(mcloc);
            log7 = log7.subtract(c);
            pk = pk.multiply(r);
        }
        return log7.round(mc);
    } else {
        /* At this point one could either forward to the log(BigDecimal) signature (implemented)
         * or decompose n into Ifactors and use an implemenation of all the prime bases.
         * Estimate of the result; convert the mc argument to an absolute error eps
         * log(n+errn) = log(n)+errn/n = log(n)+eps
         */
        double res = Math.log((double) n);
        double eps = prec2err(res, mc.getPrecision());
        /* errn = eps*n, convert absolute error in result to requirement on absolute error in input
         */
        eps *= n;

        /* Convert this absolute requirement of error in n to a relative error in n
         */
        final MathContext mcloc = new MathContext(1 + err2prec((double) n, eps));
        /* Padd n with a number of zeros to trigger the required accuracy in
         * the standard signature method
         */
        BigDecimal nb = scalePrec(new BigDecimal(n), mcloc);
        return log(nb);
    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Subtract and round according to the larger of the two ulps.
 *
 * @param x The left term./*from   ww  w. j av  a  2s  .  c  o  m*/
 * @param y The right term.
 * @return The difference x-y.
 */
static public BigDecimal subtractRound(final BigDecimal x, final BigDecimal y) {
    BigDecimal resul = x.subtract(y);
    /* The estimation of the absolute error in the result is |err(y)|+|err(x)|
     */

    double errR = Math.abs(y.ulp().doubleValue() / 2.) + Math.abs(x.ulp().doubleValue() / 2.);
    MathContext mc = new MathContext(err2prec(resul.doubleValue(), errR));

    return resul.round(mc);

}