/** * Computes a new DoubleDouble object whose value is <tt>(this - y)</tt>. * * @param y the subtrahend * @return <tt>(this - y)</tt> */ public WB_DoubleDouble subtract(final WB_DoubleDouble y) { return add(y.negate()); }
/** * Converts a string representation of a real number into a DoubleDouble value. The format * accepted is similar to the standard Java real number syntax. It is defined by the following * regular expression: * * <pre> * [<tt>+</tt>|<tt>-</tt>] {<i>digit</i>} [ <tt>.</tt> {<i>digit</i>} ] [ ( <tt>e</tt> | <tt>E</tt> ) [<tt>+</tt>|<tt>-</tt> * ] {<i>digit</i>}+ * * </pre> * * @param str the string to parse * @return the value of the parsed number * @throws NumberFormatException if <tt>str</tt> is not a valid representation of a number */ public static WB_DoubleDouble parse(final String str) throws NumberFormatException { int i = 0; final int strlen = str.length(); // skip leading whitespace while (Character.isWhitespace(str.charAt(i))) { i++; } // check for sign boolean isNegative = false; if (i < strlen) { final char signCh = str.charAt(i); if ((signCh == '-') || (signCh == '+')) { i++; if (signCh == '-') { isNegative = true; } } } // scan all digits and accumulate into an integral value // Keep track of the location of the decimal point (if any) to allow // scaling later final WB_DoubleDouble val = new WB_DoubleDouble(); int numDigits = 0; int numBeforeDec = 0; int exp = 0; while (true) { if (i >= strlen) { break; } final char ch = str.charAt(i); i++; if (Character.isDigit(ch)) { final double d = ch - '0'; val.selfMultiply(TEN); // MD: need to optimize this val.selfAdd(d); numDigits++; continue; } if (ch == '.') { numBeforeDec = numDigits; continue; } if ((ch == 'e') || (ch == 'E')) { final String expStr = str.substring(i); // this should catch any format problems with the exponent try { exp = Integer.parseInt(expStr); } catch (final NumberFormatException ex) { throw new NumberFormatException("Invalid exponent " + expStr + " in string " + str); } break; } throw new NumberFormatException( "Unexpected character '" + ch + "' at position " + i + " in string " + str); } WB_DoubleDouble val2 = val; // scale the number correctly final int numDecPlaces = numDigits - numBeforeDec - exp; if (numDecPlaces == 0) { val2 = val; } else if (numDecPlaces > 0) { final WB_DoubleDouble scale = TEN.pow(numDecPlaces); val2 = val.divide(scale); } else if (numDecPlaces < 0) { final WB_DoubleDouble scale = TEN.pow(-numDecPlaces); val2 = val.multiply(scale); } // apply leading sign, if any if (isNegative) { return val2.negate(); } return val2; }