Java Code Examples for java.math.BigDecimal#divide()

The following examples show how to use java.math.BigDecimal#divide() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: k8s-fleetman   File: DataBasicInMemoryImpl.java    License: MIT License 6 votes vote down vote up
private BigDecimal calculateSpeedInMph(String vehicleName, VehiclePosition newPosition)
{	
	TreeSet<VehiclePosition> positions = positionDatabase.get(vehicleName);
	if (positions.isEmpty()) return null;
	
	VehiclePosition posB = newPosition;
	VehiclePosition posA = positions.first(); // confusing - this is actually the last report recorded
	
	long timeAinMillis = posA.getTimestamp().getTime();
	long timeBinMillis = posB.getTimestamp().getTime();
	long timeInMillis = timeBinMillis - timeAinMillis;
	if (timeInMillis == 0) return new BigDecimal("0");
	
	BigDecimal timeInSeconds = new BigDecimal(timeInMillis / 1000.0);
			
	GlobalPosition pointA = new GlobalPosition(posA.getLat().doubleValue(), posA.getLongitude().doubleValue(), 0.0);
	GlobalPosition pointB = new GlobalPosition(posB.getLat().doubleValue(), posB.getLongitude().doubleValue(), 0.0);

	double distance = geoCalc.calculateGeodeticCurve(Ellipsoid.WGS84, pointA, pointB).getEllipsoidalDistance(); // Distance between Point A and Point B
	BigDecimal distanceInMetres = new BigDecimal (""+ distance);
	
	BigDecimal speedInMps = distanceInMetres.divide(timeInSeconds, RoundingMode.HALF_UP);
	BigDecimal milesPerHour = speedInMps.multiply(MPS_TO_MPH_FACTOR);
	return milesPerHour;
}
 
Example 2
Source Project: j2objc   File: BigDecimalArithmeticTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * divide(BigDecimal, MathContext)
 */
public void testDivideBigDecimalScaleMathContextCEILING() {
    String a = "3736186567876876578956958765675671119238118911893939591735";
    int aScale = 15;
    String b = "748766876876723342238476237823787879183470";
    int bScale = 70;
    int precision = 21;
    RoundingMode rm = RoundingMode.CEILING;
    MathContext mc = new MathContext(precision, rm);
    String c = "4.98978611802562512996E+70";
    int resScale = -50;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale);
    BigDecimal result = aNumber.divide(bNumber, mc);
    assertEquals("incorrect value", c, result.toString());
    assertEquals("incorrect scale", resScale, result.scale());
}
 
Example 3
Source Project: j2objc   File: BigDecimalArithmeticTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Divide: rounding mode is ROUND_HALF_DOWN, result is negative; distance = 1
 */
public void testDivideRoundHalfDownNeg1() {
    String a = "-92948782094488478231212478987482988798104576347813847567949855464535634534563456";
    int aScale = -24;
    String b = "74723342238476237823754692930187879183479";
    int bScale = 13;
    String c = "-1.2439055763572051712242335979928354832010167729111113605E+76";
    int resScale = -21;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale);
    BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_DOWN);
    assertEquals("incorrect value", c, result.toString());
    assertEquals("incorrect scale", resScale, result.scale());
}
 
Example 4
/**
 * 除
 */

public static BigDecimal div(Double v1, Double v2) {
    BigDecimal b1 = new BigDecimal(v1.toString());
    BigDecimal b2 = new BigDecimal(v2.toString());
    //四舍五入,保留36位小数
    return b1.divide(b2, 36, BigDecimal.ROUND_HALF_DOWN);
}
 
Example 5
/**
 * Divides the values using the biggest of the dividend precision, 
 * the divisor precision and the configured minimum precision as result
 * precision, and {@link RoundingMode#HALF_UP} as rounding mode.
 * 
 * @see #PROPERTY_MINIMUM_PRECISION
 */
@Override
public BigDecimal divide(BigDecimal dividend, BigDecimal divisor)
{
	int precision = getDivisionPrecision(dividend, divisor);
	MathContext mathContext = getMathContext(precision);
	return dividend.divide(divisor, mathContext);
}
 
Example 6
Source Project: alpha-wallet-android   File: Convert.java    License: MIT License 5 votes vote down vote up
public static String getConvertedValue(BigDecimal rawValue, int divisor)
{
    BigDecimal convertedValue = rawValue.divide(new BigDecimal(Math.pow(10, divisor)));
    DecimalFormat df = new DecimalFormat("0.#####");
    df.setRoundingMode(RoundingMode.HALF_DOWN);
    return df.format(convertedValue);
}
 
Example 7
Source Project: j2objc   File: BigDecimalArithmeticTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Divide: rounding mode is ROUND_HALF_DOWN, result is positive; distance = 1
 */
public void testDivideRoundHalfDownPos1() {
    String a = "92948782094488478231212478987482988798104576347813847567949855464535634534563456";
    int aScale = -24;
    String b = "74723342238476237823754692930187879183479";
    int bScale = 13;
    String c = "1.2439055763572051712242335979928354832010167729111113605E+76";
    int resScale = -21;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale);
    BigDecimal result = aNumber.divide(bNumber, resScale, BigDecimal.ROUND_HALF_DOWN);
    assertEquals("incorrect value", c, result.toString());
    assertEquals("incorrect scale", resScale, result.scale());
}
 
Example 8
Source Project: smart-admin   File: SmartBigDecimalUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 计算 num1 / num2 的百分比
 *
 * @param num1
 * @param num2
 * @param point 保留几位小数
 * @return String
 */
public static BigDecimal bigDecimalPercent(BigDecimal num1, BigDecimal num2, int point) {
    if (num1 == null || num2 == null) {
        return BigDecimal.ZERO;
    }
    if (equals(BigDecimal.ZERO, num2)) {
        return BigDecimal.ZERO;
    }
    BigDecimal percent = num1.divide(num2, point + 2, RoundingMode.HALF_UP);
    BigDecimal percent100 = percent.multiply(new BigDecimal(100)).setScale(point);
    return percent100;
}
 
Example 9
Source Project: SIMVA-SoS   File: SPRTMethod.java    License: Apache License 2.0 5 votes vote down vote up
public SPRTMethod(double alpha, double beta, double delta){
    this.alpha = new BigDecimal(String.valueOf(alpha));
    this.beta = new BigDecimal(String.valueOf(beta));
    this.delta = new BigDecimal(String.valueOf(delta));
    this.numSamples = 0;
    this.dm = 0;
    this.condition = true;

    pRatioA = new BigDecimal(String.valueOf(1));
    pRatioA = pRatioA.subtract(this.beta);
    pRatioA = pRatioA.divide(this.alpha, MathContext.DECIMAL32);
    pRatioB = this.beta.divide(new BigDecimal(String.valueOf(1)).subtract(this.alpha), MathContext.DECIMAL32);
}
 
Example 10
/**
 * Test FloorMod of long arguments against expected value.
 * The expected value is usually a Long but in some cases  is
 * an ArithmeticException.
 *
 * @param x dividend
 * @param y modulus
 * @param expected expected value
 */
static void testLongFloorMod(long x, long y, Object expected) {
    Object result = doFloorMod(x, y);
    if (!resultEquals(result, expected)) {
        fail("FAIL: long Math.floorMod(%d, %d) = %s; expected %s%n", x, y, result, expected);
    }

    Object strict_result = doStrictFloorMod(x, y);
    if (!resultEquals(strict_result, expected)) {
        fail("FAIL: long StrictMath.floorMod(%d, %d) = %s; expected %s%n", x, y, strict_result, expected);
    }

    try {
        // Verify the result against BigDecimal rounding mode.
        BigDecimal xD = new BigDecimal(x);
        BigDecimal yD = new BigDecimal(y);
        BigDecimal resultD = xD.divide(yD, RoundingMode.FLOOR);
        resultD = resultD.multiply(yD);
        resultD = xD.subtract(resultD);
        long fr = resultD.longValue();
        if (!result.equals(fr)) {
            fail("FAIL: Long.floorMod(%d, %d) = %d is different than BigDecimal result: %d%n", x, y, result, fr);

        }
    } catch (ArithmeticException ae) {
        if (y != 0) {
            fail("FAIL: long Math.floorMod(%d, %d); unexpected ArithmeticException from bigdecimal");
        }
    }
}
 
Example 11
Source Project: totallylazy   File: Ratio.java    License: Apache License 2.0 4 votes vote down vote up
public final BigDecimal decimalValue(MathContext mc) {
    BigDecimal numerator = new BigDecimal(this.numerator);
    BigDecimal denominator = new BigDecimal(this.denominator);

    return numerator.divide(denominator, mc);
}
 
Example 12
@Override
public BigDecimal getPrice() {

    BigDecimal n;

    BigDecimal s;

    try {

        lock.readLock().lock();

        n = notional.get();

        s = volume.get();

    } finally {
        lock.readLock().unlock();
    }

    return s.signum() == 0 ? null : n.divide(s, SATOSHI.scale(), HALF_UP);

}
 
Example 13
Source Project: phoenix   File: RoundDecimalExpression.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Produces a value half of a "step" forward in this expression's rounding scale.
 * For example with a scale of 2, "2.5" would be stepped forward to "2.505".
 */
protected final BigDecimal halfStepNextInScale(BigDecimal decimal) {
    BigDecimal step = BigDecimal.ONE.scaleByPowerOfTen(-getRoundingScale());
    BigDecimal halfStep = step.divide(BigDecimal.valueOf(2));
    return decimal.add(halfStep);
}
 
Example 14
public static ShapeletTransformFactoryOptions createSHAPELET_I_TIMED(Instances train, long time, long seed){  
    int n = train.numInstances();
    int m = utilities.multivariate_tools.MultivariateInstanceTools.channelLength(train);
    //create our search options.
    ShapeletSearchOptions.Builder searchBuilder = new ShapeletSearchOptions.Builder();
    searchBuilder.setMin(3);
    searchBuilder.setMax(m);

    //clamp K to 2000.
    int K = n > 2000 ? 2000 : n;   
    
    long numShapelets;
   
    //how much time do we have vs. how long our algorithm will take.
    BigInteger opCountTarget = new BigInteger(Long.toString(time / nanoToOp));
    BigInteger opCount = ShapeletTransformTimingUtilities.calculateOps(n, m, 1, 1);
    //multiple the total opCount by K becauise for each comparison we do across dimensions.
    opCount = opCount.multiply(BigInteger.valueOf(utilities.multivariate_tools.MultivariateInstanceTools.numDimensions(train)));
    if(opCount.compareTo(opCountTarget) == 1){
        BigDecimal oct = new BigDecimal(opCountTarget);
        BigDecimal oc = new BigDecimal(opCount);
        BigDecimal prop = oct.divide(oc, MathContext.DECIMAL64);
        
        //if we've not set a shapelet count, calculate one, based on the time set.
        numShapelets = ShapeletTransformTimingUtilities.calculateNumberOfShapelets(n,m,3,m);
        numShapelets *= prop.doubleValue();
         
         //we need to find atleast one shapelet in every series.
        searchBuilder.setSeed(seed);
        searchBuilder.setSearchType(IMPROVED_RANDOM);
        searchBuilder.setNumShapeletsToEvaluate(numShapelets);
        
        // can't have more final shapelets than we actually search through.
        K =  numShapelets > K ? K : (int) numShapelets;
    }

    
    ShapeletTransformFactoryOptions options = new ShapeletTransformFactoryOptions.ShapeletTransformOptions()
                                        .setKShapelets(K)
                                        .setSearchOptions(searchBuilder.build())
                                        .setDistanceType(ShapeletDistance.DistanceType.INDEPENDENT)
                                        .useBinaryClassValue()
                                        .useClassBalancing()
                                        .useCandidatePruning()
                                        .build();
    return options;
}
 
Example 15
Source Project: plumdo-work   File: MoneyUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static BigDecimal divide(BigDecimal value, BigDecimal divideValue) {
    return value.divide(divideValue, 2, BigDecimal.ROUND_HALF_UP);
}
 
Example 16
Source Project: warp10-platform   File: LR.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {
  
  Object o = stack.pop();
      
  if (!(o instanceof GeoTimeSerie)) {
    throw new WarpScriptException(getName() + " expects a Geo Time Series instance on top of the stack.");
  }
  
  GeoTimeSerie gts = (GeoTimeSerie) o;
  
  int n = GTSHelper.nvalues(gts);
  
  if (TYPE.DOUBLE != gts.getType() && TYPE.LONG != gts.getType()) {
    throw new WarpScriptException(getName() + " can only compute simple linear regression parameters for numerical series.");
  }
  
  BigDecimal zero = new BigDecimal(0.0D, MathContext.UNLIMITED).setScale(16);
  BigDecimal sumx = zero;
  BigDecimal sumy = zero;
  BigDecimal sumxx = zero;
  BigDecimal sumxy = zero;
  
  for (int i = 0; i < n; i++) {
    BigDecimal bd;
    if (TYPE.DOUBLE == gts.getType()) {
      bd = BigDecimal.valueOf(((Number) GTSHelper.valueAtIndex(gts, i)).doubleValue()); 
    } else {
      bd = BigDecimal.valueOf(((Number) GTSHelper.valueAtIndex(gts, i)).longValue()); 
    }
    BigDecimal tick = BigDecimal.valueOf(GTSHelper.tickAtIndex(gts, i)); 
    sumx = sumx.add(tick);
    sumy = sumy.add(bd);
    sumxx = sumxx.add(tick.multiply(tick));
    sumxy = sumxy.add(bd.multiply(tick));
  }

  BigDecimal N = BigDecimal.valueOf((double) GTSHelper.nvalues(gts));
      
  BigDecimal xybar = sumxy.divide(N, RoundingMode.HALF_UP);
  BigDecimal xbar = sumx.divide(N, RoundingMode.HALF_UP);
  BigDecimal ybar = sumy.divide(N, RoundingMode.HALF_UP);
  BigDecimal xxbar = sumxx.divide(N, RoundingMode.HALF_UP);
  
  BigDecimal betaHat = xybar.subtract(xbar.multiply(ybar)).divide(xxbar.subtract(xbar.multiply(xbar)), RoundingMode.HALF_UP);
 
  BigDecimal alphaHat = ybar.subtract(betaHat.multiply(xbar));
  
  stack.push(alphaHat.doubleValue());
  stack.push(betaHat.doubleValue());

  return stack;
}
 
Example 17
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    BigDecimal thickness = null;
    BigDecimal thicknessM = null;
    BigDecimal thicknessKm = null;
    String strTimes = req.getParameter("times");
    int times = NumberUtils.toInt(strTimes, -1);
    try {
        Locale locale = req.getLocale();
        if (strTimes != null) {
            long multipleNumber = 1;
            if (times >= 0) {
                for (int i = 0; i < times; i++) {
                    multipleNumber = multipleNumber * 2;
                }
                thickness = new BigDecimal(multipleNumber).divide(new BigDecimal(10)); // mm
                thicknessM = thickness.divide(new BigDecimal(1000)); // m
                thicknessKm = thicknessM.divide(new BigDecimal(1000)); // km
            }
        }

        StringBuilder bodyHtml = new StringBuilder();
        bodyHtml.append("<form action=\"iof\" method=\"post\">");
        bodyHtml.append(getMsg("msg.question.reach.the.moon", locale));
        bodyHtml.append("<br><br>");
        if (times >= 0) {
            bodyHtml.append(
                    "<input type=\"text\" name=\"times\" size=\"2\" maxlength=\"2\" value=" + strTimes + ">");
        } else {
            bodyHtml.append("<input type=\"text\" name=\"times\" size=\"2\" maxlength=\"2\">");
        }
        bodyHtml.append("&nbsp; ");
        bodyHtml.append(getMsg("label.times", locale) + " : ");
        if (times >= 0) {
            bodyHtml.append(thickness + " mm");
            if (thicknessM != null && thicknessKm != null) {
                bodyHtml.append(thicknessM.intValue() >= 1 && thicknessKm.intValue() < 1 ? " = " + thicknessM + " m" : "");
                bodyHtml.append(thicknessKm.intValue() >= 1 ? " = " + thicknessKm + " km" : "");
            }
            if (times == 42) {
                bodyHtml.append(" : " + getMsg("msg.answer.is.correct", locale));
            }
        }
        bodyHtml.append("<br><br>");
        bodyHtml.append("<input type=\"submit\" value=\"" + getMsg("label.calculate", locale) + "\">");
        bodyHtml.append("<br><br>");
        bodyHtml.append(getInfoMsg("msg.note.intoverflow", locale));
        bodyHtml.append("</form>");

        responseToClient(req, res, getMsg("title.intoverflow.page", locale), bodyHtml.toString());

    } catch (Exception e) {
        log.error("Exception occurs: ", e);
    }
}
 
Example 18
Source Project: nuls-v2   File: DoubleUtils.java    License: MIT License 3 votes vote down vote up
/**
 * 两个BigDecimal数据相除
 *
 * @param bd1 被除数
 * @param bd2 除数
 * @return 商
 */
public static BigDecimal div(BigDecimal bd1, BigDecimal bd2) {
    if (bd2.equals(BigDecimal.ZERO)) {
        throw new IllegalArgumentException("除数不能为0!");
    }
    return bd1.divide(bd2, 12, RoundingMode.HALF_UP);
}
 
Example 19
/**
 * Converts a value for this field to a fraction between 0 and 1.
 * <p>
 * The fractional value is between 0 (inclusive) and 1 (exclusive).
 * It can only be returned if the {@link TemporalField#range() value range} is fixed.
 * The fraction is obtained by calculation from the field range using 9 decimal
 * places and a rounding mode of {@link RoundingMode#FLOOR FLOOR}.
 * The calculation is inaccurate if the values do not run continuously from smallest to largest.
 * <p>
 * For example, the second-of-minute value of 15 would be returned as 0.25,
 * assuming the standard definition of 60 seconds in a minute.
 *
 * @param value  the value to convert, must be valid for this rule
 * @return the value as a fraction within the range, from 0 to 1, not null
 * @throws DateTimeException if the value cannot be converted to a fraction
 */
private BigDecimal convertToFraction(long value) {
    ValueRange range = field.range();
    range.checkValidValue(value, field);
    BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
    BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
    BigDecimal valueBD = BigDecimal.valueOf(value).subtract(minBD);
    BigDecimal fraction = valueBD.divide(rangeBD, 9, RoundingMode.FLOOR);
    // stripTrailingZeros bug
    return fraction.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fraction.stripTrailingZeros();
}
 
Example 20
Source Project: javamoney-lib   File: CurrentYield.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Calculates the current yield.
 *
 * @param annualCoupons    the bond's annual coupons
 * @param currentBondPrice the current bond price
 * @return the current yield
 */
public static BigDecimal calculate(MonetaryAmount annualCoupons, MonetaryAmount currentBondPrice) {
    BigDecimal annualCouponsValue = BigDecimal.valueOf(annualCoupons.getNumber().doubleValueExact());
    BigDecimal currentBondPriceValue = BigDecimal.valueOf(currentBondPrice.getNumber().doubleValueExact());

    return annualCouponsValue.divide(currentBondPriceValue, MathContext.DECIMAL64);
}