Example usage for java.lang ArithmeticException ArithmeticException

List of usage examples for java.lang ArithmeticException ArithmeticException

Introduction

In this page you can find the example usage for java.lang ArithmeticException ArithmeticException.

Prototype

public ArithmeticException(String s) 

Source Link

Document

Constructs an ArithmeticException with the specified detail message.

Usage

From source file:Main.java

/**
 * <p>//from   www .j a  v  a  2  s . c  om
 * Gets the greatest common divisor of the absolute value of two numbers,
 * using the "binary gcd" method which avoids division and modulo
 * operations. See Knuth 4.5.2 algorithm B. This algorithm is due to Josef
 * Stein (1961).
 * </p>
 * 
 * @param u a non-zero number
 * @param v a non-zero number
 * @return the greatest common divisor, never zero
 * @since 1.1
 */
public static int gcd(int u, int v) {
    if (u * v == 0) {
        return (Math.abs(u) + Math.abs(v));
    }
    // keep u and v negative, as negative integers range down to
    // -2^31, while positive numbers can only be as large as 2^31-1
    // (i.e. we can't necessarily negate a negative number without
    // overflow)
    /* assert u!=0 && v!=0; */
    if (u > 0) {
        u = -u;
    } // make u negative
    if (v > 0) {
        v = -v;
    } // make v negative
      // B1. [Find power of 2]
    int k = 0;
    while ((u & 1) == 0 && (v & 1) == 0 && k < 31) { // while u and v are
                                                     // both even...
        u /= 2;
        v /= 2;
        k++; // cast out twos.
    }
    if (k == 31) {
        throw new ArithmeticException("overflow: gcd is 2^31");
    }
    // B2. Initialize: u and v have been divided by 2^k and at least
    // one is odd.
    int t = ((u & 1) == 1) ? v : -(u / 2)/* B3 */;
    // t negative: u was odd, v may be even (t replaces v)
    // t positive: u was even, v is odd (t replaces u)
    do {
        /* assert u<0 && v<0; */
        // B4/B3: cast out twos from t.
        while ((t & 1) == 0) { // while t is even..
            t /= 2; // cast out twos
        }
        // B5 [reset max(u,v)]
        if (t > 0) {
            u = -t;
        } else {
            v = t;
        }
        // B6/B3. at this point both u and v should be odd.
        t = (v - u) / 2;
        // |u| larger: t positive (replace u)
        // |v| larger: t negative (replace v)
    } while (t != 0);
    return -u * (1 << k); // gcd is u*2^k
}

From source file:com.github.jessemull.microflex.util.IntegerUtil.java

/**
 * Safely converts a number to an integer. Loss of precision may occur. Throws
 * an arithmetic exception upon overflow.
 * @param    Number    number to parse/* w  w  w  . j  a  va 2s  . c  o  m*/
 * @return             parsed number
 * @throws   ArithmeticException    on overflow
 */
public static int toInteger(Number number) {

    /* Switch on class and convert to an int */

    String type = number.getClass().getSimpleName();
    int parsed;

    switch (type) {

    case "Byte":
        Byte by = (Byte) number;
        parsed = by.intValue();
        break;

    case "Short":
        Short sh = (Short) number;
        parsed = sh.intValue();
        break;

    case "Integer":
        Integer in = (Integer) number;
        parsed = in.intValue();
        break;

    case "Long":
        Long lo = (Long) number;
        if (!OverFlowUtil.intOverflow(lo)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = lo.intValue();
        break;

    case "Float":
        Float fl = (Float) number;
        if (!OverFlowUtil.intOverflow(fl)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = fl.intValue();
        break;

    case "BigInteger":
        BigInteger bi = (BigInteger) number;
        if (!OverFlowUtil.intOverflow(bi)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = bi.intValue();
        break;

    case "BigDecimal":
        BigDecimal bd = (BigDecimal) number;
        if (!OverFlowUtil.intOverflow(bd)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = bd.intValue();
        break;

    case "Double":
        Double db = (Double) number;
        if (!OverFlowUtil.intOverflow(db)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = db.intValue();
        break;

    default:
        throw new IllegalArgumentException(
                "Invalid type: " + type + "\nData values " + "must extend the abstract Number class.");

    }

    return parsed;
}

From source file:com.github.jessemull.microflex.util.DoubleUtil.java

/**
 * Safely converts a number to a double. Loss of precision may occur. Throws
 * an arithmetic exception upon overflow.
 * @param    Number    number to parse//from   www  .j  a va  2 s  .  com
 * @return             parsed number
 * @throws   ArithmeticException    on overflow
 */
public static double toDouble(Number number) {

    /* Switch on class and convert to double */

    String type = number.getClass().getSimpleName();
    double parsed;

    switch (type) {

    case "Byte":
        Byte by = (Byte) number;
        parsed = by.doubleValue();
        break;

    case "Short":
        Short sh = (Short) number;
        parsed = sh.doubleValue();
        break;

    case "Integer":
        Integer in = (Integer) number;
        parsed = in.doubleValue();
        break;

    case "Long":
        Long lo = (Long) number;
        parsed = lo.doubleValue();
        break;

    case "Float":
        Float fl = (Float) number;
        parsed = fl.doubleValue();
        break;

    case "BigInteger":
        BigInteger bi = (BigInteger) number;
        if (!OverFlowUtil.doubleOverflow(bi)) {
            throw new ArithmeticException("Overflow casting " + number + " to a double.");
        }
        parsed = bi.doubleValue();
        break;

    case "BigDecimal":
        BigDecimal bd = (BigDecimal) number;
        if (!OverFlowUtil.doubleOverflow(bd)) {
            throw new ArithmeticException("Overflow casting " + number + " to a double.");
        }
        parsed = bd.doubleValue();
        break;

    case "Double":
        Double db = (Double) number;
        parsed = db.doubleValue();
        break;

    default:
        throw new IllegalArgumentException(
                "Invalid type: " + type + "\nData values " + "must extend the abstract Number class.");

    }

    return parsed;
}

From source file:NumberUtils.java

/**
 * Answers the signum function of the given number
 * (i.e., <code>-1</code> if it is negative, <code>0</code>
 * if it is zero and <code>1</code> if it is positive).
 *
 * @param number//  w  ww .  j ava2  s.  co  m
 * @return int
 * @throws ArithmeticException The given number is <code>null</code> or 'not a number'.
 */
public static int signum(Number number) throws ArithmeticException {
    if (number == null || isNaN(number))
        throw new ArithmeticException("Argument must not be null or NaN.");

    if (isLongCompatible(number)) {
        long value = number.longValue();
        return value < 0 ? -1 : value == 0 ? 0 : 1;
    } else if (number instanceof BigInteger)
        return ((BigInteger) number).signum();
    else if (number instanceof BigDecimal)
        return ((BigDecimal) number).signum();
    else { // => isDoubleCompatible(number) or unknown Number type
        double value = number.doubleValue();
        return value < 0 ? -1 : value == 0 ? 0 : 1;
    }
}

From source file:jsat.distributions.MyDistributionSearch.java

/**
 * Searches the distributions that are given for a possible fit, and returns
 * what appears to be the best fit. If no suitable fit can be found, a
 * {@link MyKernelDensityEstimator} is fit to the data.
 * // w  w w  . j  a v  a  2 s. co m
 * @param v all the values from a sample
 * @param KDECutOff the cut off value used for using the KDE. Should be in
 * the range (0, 1). Values less than zero means the KDE will never be used,
 * and greater then 1 means the KDE will always be used.
 * @param possibleDistributions the array of distribution to try and fit to the data
 * @return  the distribution that provides the best fit to the data that this method could find.
 */
public static ContinuousDistribution getBestDistribution(Vec v, double KDECutOff,
        ContinuousDistribution... possibleDistributions) {
    if (v.length() == 0) {
        throw new ArithmeticException("Can not fit a distribution to an empty set");
    }
    final Pair<Boolean, Double> result = checkForDifferentValues(v);
    if (result.getFirstItem()) {
        return new SingleValueDistribution(result.getSecondItem());
    }
    //Thread Safety, clone the possible distributions

    final ContinuousDistribution[] possDistCopy = new ContinuousDistribution[possibleDistributions.length];

    for (int i = 0; i < possibleDistributions.length; i++) {
        possDistCopy[i] = possibleDistributions[i].clone();
    }

    final KSTest ksTest = new KSTest(v);

    ContinuousDistribution bestDist = null;
    double bestProb = 0;

    for (final ContinuousDistribution cd : possDistCopy) {
        try {
            cd.setUsingData(v);
            final double prob = ksTest.testDist(cd);

            if (prob > bestProb) {
                bestDist = cd;
                bestProb = prob;
            }

        } catch (final Exception ex) {

        }
    }

    ///Return the best distribution, or if somehow everythign went wrong, a normal distribution
    try {
        if (bestProb >= KDECutOff) {
            return bestDist == null ? new Normal(v.mean(), v.standardDeviation()) : bestDist.clone();
        } else {
            return new MyKernelDensityEstimator(v);
        }
    } catch (final RuntimeException ex)//Mostly likely occurs if all values are all zero
    {
        if (v.standardDeviation() == 0) {
            return null;
        }
        throw new ArithmeticException("Catistrophic faulure getting a distribution");
    }
}

From source file:us.ihmc.idl.CDR.java

public void write_type_3(int val) {
    if (val < 0)
        throw new ArithmeticException(
                "(CDR.java:134): int " + val + " cannot be cast to unsigned short. cannot be negative");
    else if (val > UNSIGNED_SHORT_MAX)
        throw new ArithmeticException("(CDR.java:134): int " + val
                + " cannot be cast to unsigned short. UNSIGNED_SHORT_MAX = " + UNSIGNED_SHORT_MAX);

    write_type_1((short) val);
}

From source file:Main.java

/**
 * <p>Internal calculation method.</p>
 * //  www.  j  a  v  a  2 s . c o  m
 * @param val  the calendar
 * @param field  the field constant
 * @param round  true to round, false to truncate
 * @throws ArithmeticException if the year is over 280 million
 */
private static void modify(Calendar val, int field, boolean round) {
    if (val.get(Calendar.YEAR) > 280000000) {
        throw new ArithmeticException("Calendar value too large for accurate calculations");
    }

    if (field == Calendar.MILLISECOND) {
        return;
    }

    // ----------------- Fix for LANG-59 ---------------------- START ---------------
    // see http://issues.apache.org/jira/browse/LANG-59
    //
    // Manually truncate milliseconds, seconds and minutes, rather than using
    // Calendar methods.

    Date date = val.getTime();
    long time = date.getTime();
    boolean done = false;

    // truncate milliseconds
    int millisecs = val.get(Calendar.MILLISECOND);
    if (!round || millisecs < 500) {
        time = time - millisecs;
    }
    if (field == Calendar.SECOND) {
        done = true;
    }

    // truncate seconds
    int seconds = val.get(Calendar.SECOND);
    if (!done && (!round || seconds < 30)) {
        time = time - (seconds * 1000L);
    }
    if (field == Calendar.MINUTE) {
        done = true;
    }

    // truncate minutes
    int minutes = val.get(Calendar.MINUTE);
    if (!done && (!round || minutes < 30)) {
        time = time - (minutes * 60000L);
    }

    // reset time
    if (date.getTime() != time) {
        date.setTime(time);
        val.setTime(date);
    }
    // ----------------- Fix for LANG-59 ----------------------- END ----------------

    boolean roundUp = false;
    for (int i = 0; i < fields.length; i++) {
        for (int j = 0; j < fields[i].length; j++) {
            if (fields[i][j] == field) {
                //This is our field... we stop looping
                if (round && roundUp) {
                    if (field == DateUtils.SEMI_MONTH) {
                        //This is a special case that's hard to generalize
                        //If the date is 1, we round up to 16, otherwise
                        //  we subtract 15 days and add 1 month
                        if (val.get(Calendar.DATE) == 1) {
                            val.add(Calendar.DATE, 15);
                        } else {
                            val.add(Calendar.DATE, -15);
                            val.add(Calendar.MONTH, 1);
                        }
                    } else {
                        //We need at add one to this field since the
                        //  last number causes us to round up
                        val.add(fields[i][0], 1);
                    }
                }
                return;
            }
        }
        //We have various fields that are not easy roundings
        int offset = 0;
        boolean offsetSet = false;
        //These are special types of fields that require different rounding rules
        switch (field) {
        case DateUtils.SEMI_MONTH:
            if (fields[i][0] == Calendar.DATE) {
                //If we're going to drop the DATE field's value,
                //  we want to do this our own way.
                //We need to subtrace 1 since the date has a minimum of 1
                offset = val.get(Calendar.DATE) - 1;
                //If we're above 15 days adjustment, that means we're in the
                //  bottom half of the month and should stay accordingly.
                if (offset >= 15) {
                    offset -= 15;
                }
                //Record whether we're in the top or bottom half of that range
                roundUp = offset > 7;
                offsetSet = true;
            }
            break;
        case Calendar.AM_PM:
            if (fields[i][0] == Calendar.HOUR_OF_DAY) {
                //If we're going to drop the HOUR field's value,
                //  we want to do this our own way.
                offset = val.get(Calendar.HOUR_OF_DAY);
                if (offset >= 12) {
                    offset -= 12;
                }
                roundUp = offset > 6;
                offsetSet = true;
            }
            break;
        }
        if (!offsetSet) {
            int min = val.getActualMinimum(fields[i][0]);
            int max = val.getActualMaximum(fields[i][0]);
            //Calculate the offset from the minimum allowed value
            offset = val.get(fields[i][0]) - min;
            //Set roundUp if this is more than half way between the minimum and maximum
            roundUp = offset > ((max - min) / 2);
        }
        //We need to remove this field
        if (offset != 0) {
            val.set(fields[i][0], val.get(fields[i][0]) - offset);
        }
    }
    throw new IllegalArgumentException("The field " + field + " is not supported");

}

From source file:edu.umd.cfar.lamp.viper.geometry.ConvexPolygon.java

/**
 * Copy constructor.//w ww  .j a  va2  s. c om
 * 
 * @param old
 *            the convex polygon to duplicate.
 */
public ConvexPolygon(ConvexPolygon old) {
    composed = false;
    if (old.edgeList != null) {
        edgeList = new ArrayList(old.edgeList.size());
        Iterator iter = old.getVerteces();
        while (iter.hasNext()) {
            try {
                addVertex((Pnt) iter.next());
            } catch (BadDataException bdx) {
                throw new ArithmeticException(bdx.getMessage());
            }
        }
    }
}

From source file:yaphyre.core.math.Vector3D.java

public Vector3D normalize() throws ArithmeticException {
    double length = length();
    if (length == 0d) {
        throw new ArithmeticException("Cannot create unit vector from zero length vector");
    } else if (length == 1d) {
        return this;
    }/*w w  w .  jav a 2s  . com*/
    return scale(1 / length);
}

From source file:eu.crisis_economics.abm.contracts.DepositAccount.java

public void deposit(final double amount) {
    if (amount < 0) {
        throw new IllegalArgumentException("Cannot deposit negative money: " + amount);
    }//from   w ww  . j  av  a 2  s  .c o m

    if (getValue() + amount > Double.MAX_VALUE) {
        throw new ArithmeticException(
                "Cannot add " + amount + ", the result is too large to represent as a double number");
    }
    getDepositHolder().increaseCashReserves(amount);
    incrementValue(amount);
    setFaceValue(getValue());
}