java.math.MathContext Java Examples

The following examples show how to use java.math.MathContext. 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 File: OffsetRangeTracker.java    From beam with Apache License 2.0 7 votes vote down vote up
@Override
public SplitResult<OffsetRange> trySplit(double fractionOfRemainder) {
  // Convert to BigDecimal in computation to prevent overflow, which may result in loss of
  // precision.
  BigDecimal cur =
      (lastAttemptedOffset == null)
          ? BigDecimal.valueOf(range.getFrom()).subtract(BigDecimal.ONE, MathContext.DECIMAL128)
          : BigDecimal.valueOf(lastAttemptedOffset);
  // split = cur + max(1, (range.getTo() - cur) * fractionOfRemainder)
  BigDecimal splitPos =
      cur.add(
          BigDecimal.valueOf(range.getTo())
              .subtract(cur, MathContext.DECIMAL128)
              .multiply(BigDecimal.valueOf(fractionOfRemainder), MathContext.DECIMAL128)
              .max(BigDecimal.ONE),
          MathContext.DECIMAL128);

  long split = splitPos.longValue();
  if (split >= range.getTo()) {
    return null;
  }
  OffsetRange res = new OffsetRange(split, range.getTo());
  this.range = new OffsetRange(range.getFrom(), split);
  return SplitResult.of(range, res);
}
 
Example #2
Source File: BigDecimalArithmeticTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * divideAndRemainder(BigDecimal, MathContext)
 */
public void testDivideAndRemainderMathContextUP() {
    String a = "3736186567876876578956958765675671119238118911893939591735";
    int aScale = 45;
    String b = "134432345432345748766876876723342238476237823787879183470";
    int bScale = 70;
    int precision = 75;
    RoundingMode rm = RoundingMode.UP;
    MathContext mc = new MathContext(precision, rm);
    String res = "277923185514690367474770683";
    int resScale = 0;
    String rem = "1.3032693871288309587558885943391070087960319452465789990E-15";
    int remScale = 70;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal bNumber = new BigDecimal(new BigInteger(b), bScale);
    BigDecimal result[] = aNumber.divideAndRemainder(bNumber, mc);
    assertEquals("incorrect quotient value", res, result[0].toString());
    assertEquals("incorrect quotient scale", resScale, result[0].scale());
    assertEquals("incorrect remainder value", rem, result[1].toString());
    assertEquals("incorrect remainder scale", remScale, result[1].scale());
}
 
Example #3
Source File: ValueDataUtil.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * 100 * A / B
 *
 * @param metaA
 * @param dataA
 * @param metaB
 * @param dataB
 * @return
 * @throws KettleValueException
 */
@Deprecated
public static Object percent1( ValueMetaInterface metaA, Object dataA, ValueMetaInterface metaB, Object dataB ) throws KettleValueException {
  if ( dataA == null || dataB == null ) {
    return null;
  }

  switch ( metaA.getType() ) {
    case ValueMetaInterface.TYPE_NUMBER:
      return divideDoubles( multiplyDoubles( 100.0D, metaA.getNumber( dataA ) ), metaB.getNumber( dataB ) );
    case ValueMetaInterface.TYPE_INTEGER:
      return divideLongs( multiplyLongs( 100L, metaA.getInteger( dataA ) ), metaB.getInteger( dataB ) );
    case ValueMetaInterface.TYPE_BIGNUMBER:
      return divideBigDecimals(
        multiplyBigDecimals( metaA.getBigNumber( dataA ), new BigDecimal( 100 ), null ), metaB
          .getBigNumber( dataB ), (MathContext) null );

    default:
      throw new KettleValueException( "The 'A/B in %' function only works on numeric data" );
  }
}
 
Example #4
Source File: BigDecimalMath.java    From nd4j with Apache License 2.0 6 votes vote down vote up
/**
 * The hyperbolic tangent.
 *
 * @param x The argument.
 * @return The tanh(x) = sinh(x)/cosh(x).
 */
static public BigDecimal tanh(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return tanh(x.negate()).negate();
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else {
        BigDecimal xhighpr = scalePrec(x, 2);
        /* tanh(x) = (1-e^(-2x))/(1+e^(-2x)) .
         */
        BigDecimal exp2x = exp(xhighpr.multiply(new BigDecimal(-2)));
        /* The error in tanh x is err(x)/cosh^2(x).
         */


        double eps = 0.5 * x.ulp().doubleValue() / Math.pow(Math.cosh(x.doubleValue()), 2.0);
        MathContext mc = new MathContext(err2prec(Math.tanh(x.doubleValue()), eps));


        return BigDecimal.ONE.subtract(exp2x).divide(BigDecimal.ONE.add(exp2x), mc);


    }
}
 
Example #5
Source File: ValueModelTest.java    From ET_Redux with Apache License 2.0 6 votes vote down vote up
/**
 * Test of setOneSigma method, of class ValueModel.
 */
@Test
public void test_SetOneSigma_double() {
    System.out.println("Testing ValueModel's setOneSigma(double newOneSigma)");
    double oneSigma = 0.0;
    ValueModel instance = new ValueModel();
    instance.setOneSigma(oneSigma);
    assertEquals(instance.getOneSigma(),new BigDecimal(oneSigma, MathContext.DECIMAL64));
    //Specific to 0
    oneSigma=0.0;
    instance.setOneSigma(oneSigma);
    assertEquals(instance.getOneSigma(),new BigDecimal(oneSigma, MathContext.DECIMAL64));
    //0 to 0
    instance.setOneSigma(oneSigma);
    assertEquals(instance.getOneSigma(),new BigDecimal(oneSigma, MathContext.DECIMAL64));
    //Specific to different specific
    oneSigma=2.0;
    instance=new ValueModel("r207_339",new BigDecimal("12.34567890"),"ABS",new BigDecimal(".123456789"), BigDecimal.ZERO);
    instance.setOneSigma(oneSigma);
    assertEquals(instance.getOneSigma(),new BigDecimal(oneSigma, ReduxConstants.mathContext15));
    //Specific to same specific
    instance.setOneSigma(oneSigma);        
    assertEquals(instance.getOneSigma(),new BigDecimal(oneSigma, ReduxConstants.mathContext15));
}
 
Example #6
Source File: BigDecimalMath.java    From nd4j with Apache License 2.0 6 votes vote down vote up
/**
 * The natural logarithm.
 *
 * @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);
    }
}
 
Example #7
Source File: TestBase.java    From OSPREY3 with GNU General Public License v2.0 6 votes vote down vote up
static EpsilonApplier<BigDecimalBounds> bigDecimalBoundsAbsolute(double epsilon) {
	return new EpsilonApplier<BigDecimalBounds>(epsilon) {

		// use a math context with fixed precision to keep additions from being really slow!
		MathContext mathContext = new MathContext(32, RoundingMode.HALF_UP);
		BigDecimal bigEpsilon = MathTools.biggen(epsilon);

		@Override
		public String term() {
			return "absolutely";
		}
		@Override
		public BigDecimalBounds apply(BigDecimalBounds bounds) {
			return new BigDecimalBounds(
				bounds.lower.subtract(bigEpsilon, mathContext),
				bounds.upper.add(bigEpsilon, mathContext)
			);
		}
	};
}
 
Example #8
Source File: RangeTests.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static int minLongConstructorTest(MathContext mc) {
    int failures = 0;
    BigDecimal bd1 = new BigDecimal(Long.MIN_VALUE,mc);
    BigDecimal bd2 = new BigDecimal(Long.MIN_VALUE).round(mc);
    if (!bd1.equals(bd2)) {
        System.out.println("new BigDecimal(long,MathContext):" +
                "long == " +
                Long.MIN_VALUE + "; result == " +
                bd1 + "; expected  == " +
                bd2
        );
        failures++;
    }
    return failures;
}
 
Example #9
Source File: Expression.java    From fin-expr with Apache License 2.0 5 votes vote down vote up
public Expression(String expr, MathContext mc) {
	assert mc != null;

	this.expr = expr.trim();
	this.mc = mc;
	initDefaultOperator();
}
 
Example #10
Source File: ValueModelTest.java    From ET_Redux with Apache License 2.0 5 votes vote down vote up
/**
 * Test of setValue method, of class ValueModel.
 */
@Test
public void test_SetValue_double() {
    System.out.println("Testing ValueModel's setValue(double newValue)");
    //Blank to blank
    double value = 0.0;
    ValueModel instance = new ValueModel();
    instance.setValue(value);
    assertEquals(instance.getValue(),new BigDecimal(value, MathContext.DECIMAL64));
    //Blank to Specific
    value = 2.0;
    instance = new ValueModel();
    instance.setValue(value);
    assertEquals(instance.getValue(),new BigDecimal(value, MathContext.DECIMAL64));
    //Specific to Blank
    value = 0.0;
    instance = new ValueModel("r206_204b", new BigDecimal( "12.34567890" ), "ABS", new BigDecimal( "0.987654321" ), BigDecimal.ZERO);
    instance.setValue(value);
    assertEquals(instance.getValue(),new BigDecimal(value, MathContext.DECIMAL64));
    //Specific to different Specific
    value = 2.0;
    instance =new ValueModel("r206_204b", new BigDecimal( "12.34567890" ), "ABS", new BigDecimal( "0.987654321" ), BigDecimal.ZERO);
    instance.setValue(value);
    assertEquals(instance.getValue(),new BigDecimal(value, MathContext.DECIMAL64));
    //Specific to same Specific
    value = 2.0;
    instance =new ValueModel("r206_204b", new BigDecimal( "2" ), "ABS", new BigDecimal( "0.987654321" ), BigDecimal.ZERO);
    instance.setValue(value);
    assertEquals(instance.getValue(),new BigDecimal(value, MathContext.DECIMAL64));
}
 
Example #11
Source File: RangeTests.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static int testRoundingFromBigInteger(BigInteger bi, int scale, MathContext mc) {
    int failures = 0;
    BigDecimal bd1 = new BigDecimal(bi,scale, mc);
    BigDecimal bd2 = (new BigDecimal(bi,scale)).round(mc);
    if (!bd1.equals(bd2)) {
        System.out.println("new BigDecimal(BigInteger,int,MathContext):" +
                "BigInteger == " +
                bi + ";  scale == " + scale + "; result == " +
                bd1 + "; expected  == " +
                bd2
        );
        failures++;
    }
    return failures;
}
 
Example #12
Source File: BigFloatTest.java    From big-math with MIT License 5 votes vote down vote up
@Test
public void testSinh() {
	Context context = context(MathContext.DECIMAL32);
	assertEquals(BigDecimalMath.sinh(BigDecimal.valueOf(0), MathContext.DECIMAL32),
			sinh(context.valueOf(0)).toBigDecimal());
	assertEquals(BigDecimalMath.sinh(BigDecimal.valueOf(0.1), MathContext.DECIMAL32),
			sinh(context.valueOf(0.1)).toBigDecimal());
}
 
Example #13
Source File: Money.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Override
public Money remainder(Number divisor) {
    if (NumberVerifier.isInfinityAndNotNaN(divisor)) {
        return new Money(BigDecimal.ZERO, getCurrency());
    }
    MathContext mc = MoneyUtils.getMathContext(monetaryContext, RoundingMode.HALF_EVEN);
    BigDecimal bd = MoneyUtils.getBigDecimal(divisor);
    return new Money(this.number.remainder(bd, mc), getCurrency(), monetaryContext);
}
 
Example #14
Source File: BigDecimalMathTest.java    From big-math with MIT License 5 votes vote down vote up
void assertRandomCalculation(int count, String functionName, Function<Random, Double> xFunction, Function<Double, Double> doubleFunction, BiFunction<BigDecimal, MathContext, BigDecimal> calculation) {
	Random random = new Random(1);

	for (int i = 0; i < count; i++) {
		int precision = random.nextInt(RANDOM_MAX_PRECISION) + 1;
		Double xDouble = xFunction.apply(random);
		BigDecimal x = BigDecimal.valueOf(xDouble);
		
		String description = functionName + "(" + x + ")";

		System.out.println("Testing " + description + " precision=" + precision);
		MathContext mathContext = new MathContext(precision);
		BigDecimal result = calculation.apply(x, mathContext);

		if (doubleFunction != null && precision > MC_CHECK_DOUBLE.getPrecision() + 4) {
               BigDecimal doubleResult = toCheck(doubleFunction.apply(xDouble));
               if (doubleResult != null) {
                   String doubleDescription = description + " vs. double function ";
                   assertBigDecimal(doubleDescription, doubleResult, result, MC_CHECK_DOUBLE);
               }
		}

		MathContext referenceMathContext = new MathContext(precision * 2 + 20);
		BigDecimal referenceResult = calculation.apply(x, referenceMathContext);
		BigDecimal expected = referenceResult.round(mathContext);
           assertBigDecimal(description, expected, result, mathContext);
	}
}
 
Example #15
Source File: BigDecimalArithmeticTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * round(BigDecimal, MathContext)
 */
public void testRoundMathContextHALF_UP() {
    String a = "3736186567876876578956958765675671119238118911893939591735";
    int aScale = 45;
    int precision = 15;
    RoundingMode rm = RoundingMode.HALF_UP;
    MathContext mc = new MathContext(precision, rm);
    String res = "3736186567876.88";
    int resScale = 2;
    BigDecimal aNumber = new BigDecimal(new BigInteger(a), aScale);
    BigDecimal result = aNumber.round(mc);
    assertEquals("incorrect quotient value", res, result.toString());
    assertEquals("incorrect quotient scale", resScale, result.scale());
}
 
Example #16
Source File: BigDecimalConstructorsTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * new BigDecimal(String value, MathContext)
 */
public void testConstrStringMathContext() {
    String a = "-238768787678287e214";
    int precision = 5;
    RoundingMode rm = RoundingMode.CEILING;
    MathContext mc = new MathContext(precision, rm);
    String res = "-23876";
    int resScale = -224;
    BigDecimal result = new BigDecimal(a, mc);
    assertEquals("incorrect value", res, result.unscaledValue().toString());
    assertEquals("incorrect scale", resScale, result.scale());
}
 
Example #17
Source File: RangeTests.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static int roundingConstructorTest() {
    int failures = 0;
    failures += testRoundingFromBigInteger(
            new BigInteger("85070591730234615847396907784232501249"),
            7, MathContext.DECIMAL64);
    failures += testRoundingFromBigInteger(
            new BigInteger("85070591730234615847396907784232501249"),
            0, MathContext.DECIMAL64);
    failures += testRoundingFromBigInteger(
            new BigInteger("85070591730234615847396907784232501249"),
            -7, MathContext.DECIMAL64);
    failures += testRoundingFromBigInteger(
            new BigInteger("85070591730234615847396907784232501249"),
            7, MathContext.DECIMAL128);
    failures += testRoundingFromBigInteger(
            new BigInteger("85070591730234615847396907784232501249"),
            177, MathContext.DECIMAL128);
    failures += testRoundingFromBigInteger(
            new BigInteger("85070591730234615847396907784232501249"),
            177, MathContext.DECIMAL32);
    failures += testRoundingFromBigInteger(
            new BigInteger("85070591730234615847396907784232501249"),
            177, MathContext.UNLIMITED);
    failures += testRoundingFromBigInteger(
            new BigInteger("85070591730234615847396907784232501249"),
            0, MathContext.UNLIMITED);
    return failures;
}
 
Example #18
Source File: CurrencyUtils.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
public static String getValueToRipple(String value) {
	String num = new BigDecimal(value).multiply(MILLION, MathContext.DECIMAL128).toString();
	int index = num.indexOf('.');
	if (index != -1) {
		num = num.substring(0, index);
	}
	return num;
}
 
Example #19
Source File: FunctionTable.java    From big-math with MIT License 5 votes vote down vote up
public static void printTableAsin() {
	MathContext mathContext = new MathContext(20);
	printTable(
			-1,
			1,
			0.01,
			Arrays.asList(
					"BigDecimalMath.asin",
					"Math.asin"),
			Arrays.asList(
					x -> BigDecimalMath.asin(x, mathContext),
					x -> BigDecimal.valueOf(Math.asin(x.doubleValue()))
					));
}
 
Example #20
Source File: MethodCallOperator.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public VisitorOperand floor() throws ODataApplicationException {
    final TypedOperand operand = parameters.get(0).asTypedOperand();
    if (operand.isNull()) {
        return operand;
    } else if (operand.isDecimalType()) {
        return new TypedOperand(
                operand.getTypedValue(BigDecimal.class).round(new MathContext(1, RoundingMode.FLOOR)),
                operand.getType());
    } else {
        throw new ODataApplicationException("Invalid type", HttpStatusCode.BAD_REQUEST.getStatusCode(),
                                            Locale.ROOT);
    }
}
 
Example #21
Source File: SimpleGraphiteClientTest.java    From simplegraphiteclient with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendFloatingPointAndLongMetrics() {
    Map<String, Number> data = new  HashMap<String, Number>();
    data.put("junit.test.metric1", 4711);
    data.put("junit.test.metric2", 4712.333);
    data.put("junit.test.metric3", 4712324723874687236L);
    data.put("junit.test.metric4", new BigDecimal(3.34, new MathContext(3)));
    data.put("junit.test.metric5", 4.89767324);
    simpleGraphiteClient.sendMetrics(data);
    assertTrue(out.toString().contains("junit.test.metric1 4711 " + currentTimestamp));
    assertTrue(out.toString().contains("junit.test.metric2 4712.333 " + currentTimestamp));
    assertTrue(out.toString().contains("junit.test.metric3 4712324723874687236 " + currentTimestamp));
    assertTrue(out.toString().contains("junit.test.metric4 3.34 " + currentTimestamp));
    assertTrue(out.toString().contains("junit.test.metric5 4.89767324 " + currentTimestamp));
}
 
Example #22
Source File: PiExample.java    From big-math with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	for (int precision = 1; precision < 2000; precision++) {
		MathContext mathContext = new MathContext(precision);
		BigDecimal pi = BigDecimalMath.pi(mathContext);
		System.out.printf("%4d : %s\n", precision, pi.toString());
	}
}
 
Example #23
Source File: BigDecimalMath.java    From big-math with MIT License 5 votes vote down vote up
private static BigDecimal logUsingNewton(BigDecimal x, MathContext mathContext) {
	// https://en.wikipedia.org/wiki/Natural_logarithm in chapter 'High Precision'
	// y = y + 2 * (x-exp(y)) / (x+exp(y))

	int maxPrecision = mathContext.getPrecision() + 20;
	BigDecimal acceptableError = ONE.movePointLeft(mathContext.getPrecision() + 1);
	//System.out.println("logUsingNewton(" + x + " " + mathContext + ") precision " + maxPrecision);

	BigDecimal result;
	int adaptivePrecision;
	double doubleX = x.doubleValue();
	if (doubleX > 0.0 && isDoubleValue(x)) {
		result = BigDecimal.valueOf(Math.log(doubleX));
		adaptivePrecision = EXPECTED_INITIAL_PRECISION;
	} else {
		result = x.divide(TWO, mathContext);
		adaptivePrecision = 1;
	}

	BigDecimal step;
	
	do {
		adaptivePrecision *= 3;
		if (adaptivePrecision > maxPrecision) {
			adaptivePrecision = maxPrecision;
		}
		MathContext mc = new MathContext(adaptivePrecision, mathContext.getRoundingMode());
		
		BigDecimal expY = BigDecimalMath.exp(result, mc);
		step = TWO.multiply(x.subtract(expY)).divide(x.add(expY), mc);
		//System.out.println("  step " + step + " adaptivePrecision=" + adaptivePrecision);
		result = result.add(step);
	} while (adaptivePrecision < maxPrecision || step.abs().compareTo(acceptableError) > 0);

	return result;
}
 
Example #24
Source File: RangeTests.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static int minLongConstructorTest() {
    int failures = 0;
    failures+=minLongConstructorTest(MathContext.UNLIMITED);
    failures+=minLongConstructorTest(MathContext.DECIMAL32);
    failures+=minLongConstructorTest(MathContext.DECIMAL64);
    failures+=minLongConstructorTest(MathContext.DECIMAL128);
    return failures;
}
 
Example #25
Source File: BigComplexMath.java    From big-math with MIT License 5 votes vote down vote up
/**
 * Calculates the square root of {@link BigComplex} x in the complex domain (√x).
 *
 * <p>See <a href="https://en.wikipedia.org/wiki/Square_root#Square_root_of_an_imaginary_number">Wikipedia: Square root (Square root of an imaginary number)</a></p>
 *
 * @param x the {@link BigComplex} to calculate the square root for
 * @param mathContext the {@link MathContext} used for the result
 * @return the calculated square root {@link BigComplex} with the precision specified in the <code>mathContext</code>
 */
public static BigComplex sqrt(BigComplex x, MathContext mathContext) {
	// https://math.stackexchange.com/questions/44406/how-do-i-get-the-square-root-of-a-complex-number
	MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode());

	BigDecimal magnitude = x.abs(mc);

	BigComplex a = x.add(magnitude, mc);
	return a.divide(a.abs(mc), mc).multiply(BigDecimalMath.sqrt(magnitude, mc), mc).round(mathContext);
}
 
Example #26
Source File: SimpleNumberFormatterTest.java    From super-csv-annotation with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    this.formatter = new SimpleNumberFormatter<>(float.class, false);
    this.formatterLenient = new SimpleNumberFormatter<>(float.class, true);
    this.formatterPrecision = new SimpleNumberFormatter<>(float.class, true, new MathContext(4, RoundingMode.DOWN));
    
}
 
Example #27
Source File: ExtendedDecimalTest.java    From ion-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testToString()
{
    assertEquals("-0", NEG_ZERO_0.toString());
    assertEquals("-0", NEG_ZERO_0.toEngineeringString());
    assertEquals("-0", NEG_ZERO_0.toPlainString());

    assertEquals("-0.000", NEG_ZERO_3.toString());
    assertEquals("-0.000", NEG_ZERO_3.toEngineeringString());
    assertEquals("-0.000", NEG_ZERO_3.toPlainString());

    assertEquals("-0", negativeZero(0, MathContext.UNLIMITED).toString());
}
 
Example #28
Source File: BigDecimalConstructorsTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * new BigDecimal(double, MathContext)
 */
public void testConstrDoubleMathContext() {
    double a = 732546982374982347892379283571094797.287346782359284756;
    int precision = 21;
    RoundingMode rm = RoundingMode.CEILING;
    MathContext mc = new MathContext(precision, rm);
    String res = "732546982374982285074";
    int resScale = -15;
    BigDecimal result = new BigDecimal(a, mc);
    assertEquals("incorrect value", res, result.unscaledValue().toString());
    assertEquals("incorrect scale", resScale, result.scale());
}
 
Example #29
Source File: PerformanceBigDecimalMath.java    From big-math with MIT License 5 votes vote down vote up
@SafeVarargs
private static void performanceReportOverPrecision(String name, BigDecimal value, int precisionStart, int precisionEnd, int precisionStep, int repeats, List<String> functionNames, BiFunction<BigDecimal, MathContext, BigDecimal>... calculations) {
	StopWatch stopWatch = new StopWatch();
	System.out.println("Writing  " + name);

	try (PrintWriter writer = new PrintWriter(new FileWriter(OUTPUT_DIRECTORY + name))) {
		performanceReportOverPrecision(writer, value, precisionStart, precisionEnd, precisionStep, repeats, functionNames, calculations);
	} catch (IOException ex) {
		ex.printStackTrace();
	}

	System.out.println("Finished in " + stopWatch);
}
 
Example #30
Source File: ResultsFilter.java    From thunderstorm with GNU General Public License v3.0 5 votes vote down vote up
void addNewFilter(String paramName, double greaterThan, double lessThan) {
    String formula = getFilterFormula().trim();
    StringBuilder sb = new StringBuilder(formula);
    if(!formula.isEmpty()) {
        sb.append(" & ");
    }
    sb.append("(");
    sb.append(paramName).append(" > ").append(BigDecimal.valueOf(greaterThan).round(new MathContext(6)).toString());
    sb.append(" & ");
    sb.append(paramName).append(" < ").append(BigDecimal.valueOf(lessThan).round(new MathContext(6)).toString());
    sb.append(")");
    setFilterFormula(sb.toString());
}