简体   繁体   中英

Which rounding method is used in Java when operating on floating point numbers?

The language is Java and the machine is a normal PC with an Intel processor. The type is double.

Floating point numbers can't represent exactly every fractional number, the result of the operations like division or subtraction are somehow rounded to some near floating point representation.

I am asking whether the used rounding strategy is:

  1. rounding away from zero
  2. rounding towards zero
  3. rounding towards negative infinity
  4. rounding towards positive infinity
  5. rounding to nearest (half up)
  6. rounding to nearest (half down)
  7. rounding to nearest (half even)

Java Virtual Machine Floating-Point Arithmetic and IEEE 754

...

  • The rounding operations of the Java Virtual Machine always use IEEE 754 round to nearest mode. Inexact results are rounded to the nearest representable value, with ties going to the value with a zero least-significant bit . This is the IEEE 754 default mode. But Java Virtual Machine instructions that convert values of floating-point types to values of integral types round toward zero. The Java Virtual Machine does not give any means to change the floating-point rounding mode .

Thus, as Patricia Shanahan already answered in the comments, JVM's rounding mode is fixed to #7 rounding to nearest (half even) from your list. However this only applies to float-to-float rounding. Float-to-integer rounding uses #2 rounding towards zero

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM