Package java.math

Examples of java.math.MathContext


        nzeros = prec - (origPrec - 1);
    } else {
        compPrec = prec + 1;
    }

    MathContext mc = new MathContext(compPrec);
    BigDecimal v
        = new BigDecimal(value.unscaledValue(), scale, mc);

    BigDecimalLayout bdl
         = new BigDecimalLayout(v.unscaledValue(), v.scale(),
              BigDecimalLayoutForm.SCIENTIFIC);

    char[] mant = bdl.mantissa();

    // Add a decimal point if necessary.  The mantissa may not
    // contain a decimal point if the scale is zero (the internal
    // representation has no fractional part) or the original
    // precision is one. Append a decimal point if '#' is set or if
    // we require zero padding to get to the requested precision.
     if ((origPrec == 1 || !bdl.hasDot())
         && (nzeros > 0 || (f.contains(Flags.ALTERNATE))))
         mant = addDot(mant);

    // Add trailing zeros in the case precision is greater than
    // the number of available digits after the decimal separator.
    mant = trailingZeros(mant, nzeros);

    char[] exp = bdl.exponent();
    int newW = width;
    if (width != -1)
        newW = adjustWidth(width - exp.length - 1, f, neg);
    localizedMagnitude(sb, mant, f, newW, null);

    sb.append(f.contains(Flags.UPPERCASE) ? 'E' : 'e');

    Flags flags = f.dup().remove(Flags.GROUP);
    char sign = exp[0];
    assert(sign == '+' || sign == '-');
    sb.append(exp[0]);

    char[] tmp = new char[exp.length - 1];
    System.arraycopy(exp, 1, tmp, 0, exp.length - 1);
    sb.append(localizedMagnitude(null, tmp, flags, -1, null));
      } else if (c == Conversion.DECIMAL_FLOAT) {
    // Create a new BigDecimal with the desired precision.
    int prec = (precision == -1 ? 6 : precision);
    int scale = value.scale();
                if (scale > prec) {
                    // more "scale" digits than the requested "precision
                    int compPrec = value.precision();
                    if (compPrec <= scale) {
                        // case of 0.xxxxxx
                        value = value.setScale(prec, RoundingMode.HALF_UP);
                    } else {
                        compPrec -= (scale - prec);
                        value = new BigDecimal(value.unscaledValue(),
                                               scale,
                                               new MathContext(compPrec));
                    }
                }
                BigDecimalLayout bdl = new BigDecimalLayout(
                                           value.unscaledValue(),
                                           value.scale(),
View Full Code Here


   * @see #PROPERTY_MINIMUM_PRECISION
   */
  public BigDecimal divide(BigDecimal dividend, BigDecimal divisor)
  {
    int precision = getDivisionPrecision(dividend, divisor);
    MathContext mathContext = getMathContext(precision);
    return dividend.divide(divisor, mathContext);
  }
View Full Code Here

     
      mathContexts.set(newContexts);
      contexts = newContexts;
    }
   
    MathContext mathContext = contexts[idx];
    if (mathContext == null)
    {
      mathContext = new MathContext(precision, RoundingMode.HALF_UP);
      contexts[idx] = mathContext;
    }
    return mathContext;
  }
View Full Code Here

        }

        BigDecimal res = value.multiply(val.value);
        if (res.precision() > digits) {
            // TODO: rounding mode should not be hard-coded. See #mode.
            res = res.round(new MathContext(digits,  RoundingMode.HALF_UP));
        }
        return new RubyBigDecimal(runtime, res).setResult();
    }
View Full Code Here

            // Note: MRI has a very non-trivial way of calculating the precision,
            // so we use very simple approximation here:
            int precision = (-times + 4) * (getAllDigits().length() + 4);

            return new RubyBigDecimal(getRuntime(),
                    value.pow(times, new MathContext(precision, RoundingMode.HALF_UP)));
        } else {
            return new RubyBigDecimal(getRuntime(), value.pow(times));
        }
    }
View Full Code Here

        if (res != null) {
            return res;
        }
        RoundingMode roundMode = getRoundingMode(runtime);
        return new RubyBigDecimal(runtime, value.add(
                val.value, new MathContext(prec, roundMode))); // TODO: why this: .setResult();
    }
View Full Code Here

            return op_quo(context, other);
        } else {
            // TODO: better algorithm to set precision needed
            int prec = Math.max(200, scale);
            return new RubyBigDecimal(getRuntime(),
                    value.divide(val.value, new MathContext(prec, RoundingMode.HALF_UP))).setResult(scale);
        }
    }
View Full Code Here

        }

        n += 4; // just in case, add a bit of extra precision

        return new RubyBigDecimal(getRuntime(),
                bigSqrt(this.value, new MathContext(n, RoundingMode.HALF_UP))).setResult();
    }
View Full Code Here

       
        int precision = value.precision() - value.scale() + n;
       
        if (precision > 0) {
            return new RubyBigDecimal(getRuntime(),
                    value.round(new MathContext(precision, RoundingMode.DOWN)));
        } else {
            // TODO: proper sign
            return new RubyBigDecimal(getRuntime(), BigDecimal.ZERO);
        }
    }
View Full Code Here

      }

      // Initial precision is that of double numbers 2^63/2 ~ 4E18
      int BITS = 62;                              // 63-1 an even number of number bits
      int nInit = 16;                             // precision seems 16 to 18 digits
      MathContext nMC = new MathContext(18, RoundingMode.HALF_DOWN);

      // Iteration variables, for the square root x and the reciprocal v
      BigDecimal x = null, e = null;              // initial x:  x0 ~ sqrt()
      BigDecimal v = null, g = null;              // initial v:  v0 = 1/(2*x)

      // Estimate the square root with the foremost 62 bits of squarD
      BigInteger bi = squarD.unscaledValue();     // bi and scale are a tandem
      int biLen = bi.bitLength();
      int shift = Math.max(0, biLen - BITS + (biLen%2 == 0 ? 0 : 1));   // even shift..
      bi = bi.shiftRight(shift);                  // ..floors to 62 or 63 bit BigInteger

      double root = Math.sqrt(bi.doubleValue());
      BigDecimal halfBack = new BigDecimal(BigInteger.ONE.shiftLeft(shift/2));

      int scale = squarD.scale();
      if (scale % 2 == 1) {
          root *= SQRT_10;                        // 5 -> 2, -5 -> -3 need half a scale more..
      }
      scale = (int) Math.floor(scale/2.);         // ..where 100 -> 10 shifts the scale

      // Initial x - use double root - multiply by halfBack to unshift - set new scale
      x = new BigDecimal(root, nMC);
      x = x.multiply(halfBack, nMC);              // x0 ~ sqrt()
      if (scale != 0) {
          x = x.movePointLeft(scale);
      }

      if (prec < nInit) {                // for prec 15 root x0 must surely be OK
          return x.round(rootMC);        // return small prec roots without iterations
      }

      // Initial v - the reciprocal
      v = BigDecimal.ONE.divide(TWO.multiply(x), nMC);        // v0 = 1/(2*x)

      // Collect iteration precisions beforehand
      List<Integer> nPrecs = new ArrayList<Integer>();

      assert nInit > 3 : "Never ending loop!";                // assume nInit = 16 <= prec

      // Let m be the exact digits precision in an earlier! loop
      for (int m = prec + 1; m > nInit; m = m/2 + (m > 100 ? 1 : 2)) {
          nPrecs.add(m);
      }

      // The loop of "Square Root by Coupled Newton Iteration"
      for (int i = nPrecs.size() - 1; i > -1; i--) {
          // Increase precision - next iteration supplies n exact digits
          nMC = new MathContext(nPrecs.get(i), (i%2 == 1) ? RoundingMode.HALF_UP :
                                                          RoundingMode.HALF_DOWN);

          // Next x                                        // e = d - x^2
          e = squarD.subtract(x.multiply(x, nMC), nMC);
          if (i != 0) {
View Full Code Here

TOP

Related Classes of java.math.MathContext

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.