| 1 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 2 | // Copyright (c) 2018 Saxonica Limited. |
| 3 | // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. |
| 4 | // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 5 | // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. |
| 6 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 7 | |
| 8 | package net.sf.saxon.value; |
| 9 | |
| 10 | import net.sf.saxon.expr.sort.AtomicMatchKey; |
| 11 | import net.sf.saxon.expr.sort.AtomicSortComparer; |
| 12 | import net.sf.saxon.expr.sort.DoubleSortComparer; |
| 13 | import net.sf.saxon.trans.XPathException; |
| 14 | import net.sf.saxon.tree.util.FastStringBuffer; |
| 15 | import net.sf.saxon.type.AtomicType; |
| 16 | import net.sf.saxon.type.BuiltInAtomicType; |
| 17 | import net.sf.saxon.type.ValidationException; |
| 18 | |
| 19 | import java.math.BigDecimal; |
| 20 | import java.math.RoundingMode; |
| 21 | |
| 22 | /** |
| 23 | * A numeric (double precision floating point) value |
| 24 | */ |
| 25 | |
| 26 | public final class DoubleValue extends NumericValue { |
| 27 | |
| 28 | public static final DoubleValue ZERO = new DoubleValue(0.0); |
| 29 | public static final DoubleValue NEGATIVE_ZERO = new DoubleValue(-0.0); |
| 30 | public static final DoubleValue ONE = new DoubleValue(1.0); |
| 31 | public static final DoubleValue NaN = new DoubleValue(Double.NaN); |
| 32 | |
| 33 | private double value; |
| 34 | |
| 35 | /** |
| 36 | * Constructor supplying a double |
| 37 | * |
| 38 | * @param value the value of the NumericValue |
| 39 | */ |
| 40 | |
| 41 | public DoubleValue(double value) { |
| 42 | this.value = value; |
| 43 | typeLabel = BuiltInAtomicType.DOUBLE; |
| 44 | } |
| 45 | |
| 46 | /** |
| 47 | * Constructor supplying a double and an AtomicType, for creating |
| 48 | * a value that belongs to a user-defined subtype of xs:double. It is |
| 49 | * the caller's responsibility to ensure that the supplied value conforms |
| 50 | * to the supplied type. |
| 51 | * |
| 52 | * @param value the value of the NumericValue |
| 53 | * @param type the type of the value. This must be a subtype of xs:double, and the |
| 54 | * value must conform to this type. The methosd does not check these conditions. |
| 55 | */ |
| 56 | |
| 57 | public DoubleValue(double value, AtomicType type) { |
| 58 | this.value = value; |
| 59 | typeLabel = type; |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Static factory method (for convenience in compiled bytecode) |
| 64 | * |
| 65 | * @param value the value of the double |
| 66 | * @return a new DoubleValue |
| 67 | */ |
| 68 | |
| 69 | public static DoubleValue makeDoubleValue(double value) { |
| 70 | return new DoubleValue(value); |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * Create a copy of this atomic value, with a different type label |
| 75 | * |
| 76 | * @param typeLabel the type label of the new copy. The caller is responsible for checking that |
| 77 | * the value actually conforms to this type. |
| 78 | */ |
| 79 | |
| 80 | /*@NotNull*/ |
| 81 | public AtomicValue copyAsSubType(AtomicType typeLabel) { |
| 82 | DoubleValue v = new DoubleValue(value); |
| 83 | v.typeLabel = typeLabel; |
| 84 | return v; |
| 85 | } |
| 86 | |
| 87 | /** |
| 88 | * Determine the primitive type of the value. This delivers the same answer as |
| 89 | * getItemType().getPrimitiveItemType(). The primitive types are |
| 90 | * the 19 primitive types of XML Schema, plus xs:integer, xs:dayTimeDuration and xs:yearMonthDuration, |
| 91 | * and xs:untypedAtomic. For external objects, the result is AnyAtomicType. |
| 92 | */ |
| 93 | |
| 94 | public BuiltInAtomicType getPrimitiveType() { |
| 95 | return BuiltInAtomicType.DOUBLE; |
| 96 | } |
| 97 | |
| 98 | /** |
| 99 | * Return this numeric value as a double |
| 100 | * |
| 101 | * @return the value as a double |
| 102 | */ |
| 103 | |
| 104 | public double getDoubleValue() { |
| 105 | return value; |
| 106 | } |
| 107 | |
| 108 | /** |
| 109 | * Get the numeric value converted to a float |
| 110 | * |
| 111 | * @return a float representing this numeric value; NaN if it cannot be converted |
| 112 | */ |
| 113 | @Override |
| 114 | public float getFloatValue() { |
| 115 | return (float) value; |
| 116 | } |
| 117 | |
| 118 | /** |
| 119 | * Get the numeric value converted to a decimal |
| 120 | * |
| 121 | * @return a decimal representing this numeric value; |
| 122 | * @throws ValidationException |
| 123 | * if the value cannot be converted, for example if it is NaN or infinite |
| 124 | */ |
| 125 | @Override |
| 126 | public BigDecimal getDecimalValue() throws ValidationException { |
| 127 | try { |
| 128 | return new BigDecimal(value); |
| 129 | } catch (NumberFormatException e) { |
| 130 | throw new ValidationException(e); |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | /** |
| 135 | * Return the numeric value as a Java long. |
| 136 | * |
| 137 | * @return the numeric value as a Java long. This performs truncation |
| 138 | * towards zero. |
| 139 | * @throws net.sf.saxon.trans.XPathException |
| 140 | * if the value cannot be converted |
| 141 | */ |
| 142 | @Override |
| 143 | public long longValue() throws XPathException { |
| 144 | return (long) value; |
| 145 | } |
| 146 | |
| 147 | /** |
| 148 | * Get the hashCode. This must conform to the rules for other NumericValue hashcodes |
| 149 | * |
| 150 | * @see NumericValue#hashCode |
| 151 | */ |
| 152 | |
| 153 | public int hashCode() { |
| 154 | if (value > Integer.MIN_VALUE && value < Integer.MAX_VALUE) { |
| 155 | return (int) value; |
| 156 | } else { |
| 157 | return Double.valueOf(value).hashCode(); |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | /** |
| 162 | * Test whether the value is the double/float value NaN |
| 163 | */ |
| 164 | |
| 165 | public boolean isNaN() { |
| 166 | return Double.isNaN(value); |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * Get the effective boolean value |
| 171 | * |
| 172 | * @return the effective boolean value (true unless the value is zero or NaN) |
| 173 | */ |
| 174 | public boolean effectiveBooleanValue() { |
| 175 | return value != 0.0 && !Double.isNaN(value); |
| 176 | } |
| 177 | |
| 178 | /** |
| 179 | * Convert the double to a string according to the XPath 2.0 rules |
| 180 | * @return the string value |
| 181 | */ |
| 182 | // public String getStringValue() { |
| 183 | // return doubleToString(value).toString(); //, Double.toString(value)).toString(); |
| 184 | // } |
| 185 | |
| 186 | /** |
| 187 | * Convert the double to a string according to the XPath 2.0 rules |
| 188 | * |
| 189 | * @return the string value |
| 190 | */ |
| 191 | public CharSequence getPrimitiveStringValue() { |
| 192 | return doubleToString(value); |
| 193 | } |
| 194 | |
| 195 | /** |
| 196 | * Get the canonical lexical representation as defined in XML Schema. This is not always the same |
| 197 | * as the result of casting to a string according to the XPath rules. For xs:double, the canonical |
| 198 | * representation always uses exponential notation. |
| 199 | */ |
| 200 | |
| 201 | public CharSequence getCanonicalLexicalRepresentation() { |
| 202 | FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C16); |
| 203 | return FloatingPointConverter.appendDouble(fsb, value, true); |
| 204 | } |
| 205 | |
| 206 | /** |
| 207 | * Internal method used for conversion of a double to a string |
| 208 | * |
| 209 | * @param value the actual value |
| 210 | * @return the value converted to a string, according to the XPath casting rules. |
| 211 | */ |
| 212 | |
| 213 | public static CharSequence doubleToString(double value) { |
| 214 | return FloatingPointConverter.appendDouble(new FastStringBuffer(FastStringBuffer.C16), value, false); |
| 215 | } |
| 216 | |
| 217 | |
| 218 | /** |
| 219 | * Negate the value |
| 220 | */ |
| 221 | |
| 222 | public NumericValue negate() { |
| 223 | return new DoubleValue(-value); |
| 224 | } |
| 225 | |
| 226 | /** |
| 227 | * Implement the XPath floor() function |
| 228 | */ |
| 229 | |
| 230 | public NumericValue floor() { |
| 231 | return new DoubleValue(Math.floor(value)); |
| 232 | } |
| 233 | |
| 234 | /** |
| 235 | * Implement the XPath ceiling() function |
| 236 | */ |
| 237 | |
| 238 | public NumericValue ceiling() { |
| 239 | return new DoubleValue(Math.ceil(value)); |
| 240 | } |
| 241 | |
| 242 | /** |
| 243 | * Implement the XPath round() function |
| 244 | */ |
| 245 | |
| 246 | public NumericValue round(int scale) { |
| 247 | if (Double.isNaN(value)) { |
| 248 | return this; |
| 249 | } |
| 250 | if (Double.isInfinite(value)) { |
| 251 | return this; |
| 252 | } |
| 253 | if (value == 0.0) { |
| 254 | return this; // handles the negative zero case |
| 255 | } |
| 256 | |
| 257 | if (scale == 0 && value > Long.MIN_VALUE && value < Long.MAX_VALUE) { |
| 258 | if (value >= -0.5 && value < 0.0) { |
| 259 | return new DoubleValue(-0.0); |
| 260 | } |
| 261 | return new DoubleValue(Math.round(value)); |
| 262 | } |
| 263 | |
| 264 | // Convert to a scaled integer, by multiplying by 10^scale |
| 265 | |
| 266 | double factor = Math.pow(10, scale + 1); |
| 267 | double d = Math.abs(value * factor); |
| 268 | |
| 269 | if (Double.isInfinite(d)) { |
| 270 | // double arithmetic has overflowed - do it in decimal |
| 271 | BigDecimal dec = new BigDecimal(value); |
| 272 | dec = dec.setScale(scale, RoundingMode.HALF_UP); |
| 273 | return new DoubleValue(dec.doubleValue()); |
| 274 | } |
| 275 | |
| 276 | // Now apply any rounding needed, using the "round half to even" rule***CHANGE |
| 277 | |
| 278 | double rem = d % 10; |
| 279 | if (rem >= 5) { |
| 280 | d += 10 - rem; |
| 281 | } else if (rem < 5) { |
| 282 | d -= rem; |
| 283 | } |
| 284 | |
| 285 | // Now convert back to the original magnitude |
| 286 | |
| 287 | d /= factor; |
| 288 | if (value < 0) { |
| 289 | d = -d; |
| 290 | } |
| 291 | return new DoubleValue(d); |
| 292 | } |
| 293 | |
| 294 | /** |
| 295 | * Implement the XPath round-to-half-even() function |
| 296 | */ |
| 297 | |
| 298 | public NumericValue roundHalfToEven(int scale) { |
| 299 | if (Double.isNaN(value)) return this; |
| 300 | if (Double.isInfinite(value)) return this; |
| 301 | if (value == 0.0) return this; // handles the negative zero case |
| 302 | |
| 303 | // Convert to a scaled integer, by multiplying by 10^scale |
| 304 | |
| 305 | double factor = Math.pow(10, scale + 1); |
| 306 | double d = Math.abs(value * factor); |
| 307 | |
| 308 | if (Double.isInfinite(d)) { |
| 309 | // double arithmetic has overflowed - do it in decimal |
| 310 | BigDecimal dec = new BigDecimal(value); |
| 311 | dec = dec.setScale(scale, RoundingMode.HALF_EVEN); |
| 312 | return new DoubleValue(dec.doubleValue()); |
| 313 | } |
| 314 | |
| 315 | // Now apply any rounding needed, using the "round half to even" rule |
| 316 | |
| 317 | double rem = d % 10; |
| 318 | if (rem > 5) { |
| 319 | d += 10 - rem; |
| 320 | } else if (rem < 5) { |
| 321 | d -= rem; |
| 322 | } else { |
| 323 | // round half to even - check the last bit |
| 324 | if ((d % 20) == 15) { |
| 325 | d += 5; |
| 326 | } else { |
| 327 | d -= 5; |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | // Now convert back to the original magnitude |
| 332 | |
| 333 | d /= factor; |
| 334 | if (value < 0) { |
| 335 | d = -d; |
| 336 | } |
| 337 | return new DoubleValue(d); |
| 338 | |
| 339 | } |
| 340 | |
| 341 | /** |
| 342 | * Determine whether the value is negative, zero, or positive |
| 343 | * |
| 344 | * @return -1 if negative, 0 if zero (including negative zero) or NaN, +1 if positive |
| 345 | */ |
| 346 | |
| 347 | public int signum() { |
| 348 | if (Double.isNaN(value)) { |
| 349 | return 0; |
| 350 | } |
| 351 | return value > 0 ? 1 : value == 0 ? 0 : -1; |
| 352 | } |
| 353 | |
| 354 | /** |
| 355 | * Ask whether this value is negative zero |
| 356 | * |
| 357 | * @return true if this value is float or double negative zero |
| 358 | */ |
| 359 | @Override |
| 360 | public boolean isNegativeZero() { |
| 361 | return value == 0.0 && (Double.doubleToLongBits(value) & FloatingPointConverter.DOUBLE_SIGN_MASK) != 0; |
| 362 | } |
| 363 | |
| 364 | /** |
| 365 | * Determine whether the value is a whole number, that is, whether it compares |
| 366 | * equal to some integer |
| 367 | */ |
| 368 | |
| 369 | public boolean isWholeNumber() { |
| 370 | return value == Math.floor(value) && !Double.isInfinite(value); |
| 371 | } |
| 372 | |
| 373 | /** |
| 374 | * Test whether a number is a possible subscript into a sequence, that is, |
| 375 | * a whole number greater than zero and less than 2^31 |
| 376 | * |
| 377 | * @return the number as an int if it is a possible subscript, or -1 otherwise |
| 378 | */ |
| 379 | @Override |
| 380 | public int asSubscript() { |
| 381 | if (isWholeNumber() && value > 0 && value <= Integer.MAX_VALUE) { |
| 382 | return (int)value; |
| 383 | } else { |
| 384 | return -1; |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | /** |
| 389 | * Get the absolute value as defined by the XPath abs() function |
| 390 | * |
| 391 | * @return the absolute value |
| 392 | * @since 9.2 |
| 393 | */ |
| 394 | |
| 395 | public NumericValue abs() { |
| 396 | if (value > 0.0) { |
| 397 | return this; |
| 398 | } else { |
| 399 | return new DoubleValue(Math.abs(value)); |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | /** |
| 404 | * Compare the value to a long. |
| 405 | * |
| 406 | * @param other the value to be compared with |
| 407 | * @return -1 if this is less, 0 if this is equal, +1 if this is greater or if this is NaN |
| 408 | */ |
| 409 | |
| 410 | public int compareTo(long other) { |
| 411 | double otherDouble = (double) other; |
| 412 | if (value == otherDouble) { |
| 413 | return 0; |
| 414 | } |
| 415 | return value < otherDouble ? -1 : +1; |
| 416 | } |
| 417 | |
| 418 | /** |
| 419 | * Get an object that implements XML Schema comparison semantics |
| 420 | */ |
| 421 | |
| 422 | public Comparable getSchemaComparable() { |
| 423 | // Convert negative to positive zero because Double.compareTo() does the wrong thing |
| 424 | // Note that for NaN, we return NaN, and rely on the user of the Comparable to use it in a way |
| 425 | // that ensures NaN != NaN. |
| 426 | return value == 0.0 ? 0.0 : value; |
| 427 | } |
| 428 | |
| 429 | /** |
| 430 | * Get a value whose equals() method follows the "same key" rules for comparing the keys of a map. |
| 431 | * |
| 432 | * @return a value with the property that the equals() and hashCode() methods follow the rules for comparing |
| 433 | * keys in maps. |
| 434 | */ |
| 435 | |
| 436 | @Override |
| 437 | public AtomicMatchKey asMapKey() { |
| 438 | if (isNaN()) { |
| 439 | return AtomicSortComparer.COLLATION_KEY_NaN; |
| 440 | } else if (Double.isInfinite(value)) { |
| 441 | return this; |
| 442 | } else { |
| 443 | try { |
| 444 | return new BigDecimalValue(value); |
| 445 | } catch (ValidationException e) { |
| 446 | // We have already ruled out the values that fail (NaN and INF) |
| 447 | throw new AssertionError(e); |
| 448 | } |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | /** |
| 453 | * Determine whether two atomic values are identical, as determined by XML Schema rules. This is a stronger |
| 454 | * test than equality (even schema-equality); for example two dateTime values are not identical unless |
| 455 | * they are in the same timezone. |
| 456 | * <p>Note that even this check ignores the type annotation of the value. The integer 3 and the short 3 |
| 457 | * are considered identical, even though they are not fully interchangeable. "Identical" means the |
| 458 | * same point in the value space, regardless of type annotation.</p> |
| 459 | * <p>NaN is identical to itself.</p> |
| 460 | * |
| 461 | * @param v the other value to be compared with this one |
| 462 | * @return true if the two values are identical, false otherwise. |
| 463 | */ |
| 464 | |
| 465 | public boolean isIdentical(/*@NotNull*/ AtomicValue v) { |
| 466 | return v instanceof DoubleValue && DoubleSortComparer.getInstance().comparesEqual(this, v); |
| 467 | } |
| 468 | |
| 469 | /* |
| 470 | * Diagnostic method: print the sign, exponent, and significand |
| 471 | * @param d the double to be diagnosed |
| 472 | */ |
| 473 | |
| 474 | // public static void printInternalForm(double d) { |
| 475 | // System.err.println("==== Double " + d + " ===="); |
| 476 | // long bits = Double.doubleToLongBits(d); |
| 477 | // System.err.println("Internal form: " + Long.toHexString(bits)); |
| 478 | // if (bits == 0x7ff0000000000000L) { |
| 479 | // System.err.println("+Infinity"); |
| 480 | // } else if (bits == 0xfff0000000000000L) { |
| 481 | // System.err.println("-Infinity"); |
| 482 | // } else if (bits == 0x7ff8000000000000L) { |
| 483 | // System.err.println("NaN"); |
| 484 | // } else { |
| 485 | // int s = ((bits >> 63) == 0) ? 1 : -1; |
| 486 | // int e = (int)((bits >> 52) & 0x7ffL); |
| 487 | // long m = (e == 0) ? |
| 488 | // (bits & 0xfffffffffffffL) << 1 : |
| 489 | // (bits & 0xfffffffffffffL) | 0x10000000000000L; |
| 490 | // int exponent = e-1075; |
| 491 | // System.err.println("Sign: " + s); |
| 492 | // System.err.println("Raw Exponent: " + e); |
| 493 | // System.err.println("Exponent: " + exponent); |
| 494 | // System.err.println("Significand: " + m); |
| 495 | // BigDecimal dec = BigDecimal.valueOf(m); |
| 496 | // if (exponent > 0) { |
| 497 | // dec = dec.multiply(new BigDecimal(BigInteger.valueOf(2).pow(exponent))); |
| 498 | // } else { |
| 499 | // // Next line is sometimes failing, e.g. on -3.62e-5. Not investigated. |
| 500 | // dec = dec.divide(new BigDecimal(BigInteger.valueOf(2).pow(-exponent)), BigDecimal.ROUND_HALF_EVEN); |
| 501 | // } |
| 502 | // System.err.println("Exact value: " + (s>0?"":"-") + dec); |
| 503 | // } |
| 504 | // } |
| 505 | |
| 506 | // public static DoubleValue fromInternalForm(String hex) { |
| 507 | // return new DoubleValue(Double.longBitsToDouble(Long.parseLong(hex, 16))); |
| 508 | // |
| 509 | // } |
| 510 | |
| 511 | |
| 512 | } |
| 513 |