截断除法和地板除法有什么区别?

What is the difference between Truncated Division and Floored division?

我需要使用数学方法的理论答案。它们之间在数学上有什么区别吗?它们对编程语言有何影响。

您要除以整数,因此结果将四舍五入为最接近的整数。请改用浮点变量。

比如你问题的第二部分,1.0/2.0 = 0.5。

根据 Java 术语,RoundingMode 的 javadoc 最好回答“截断除法”与“地板除法”的问题:

DOWN
Rounding mode to round towards zero. Never increments the digit prior to a discarded fraction (i.e., truncates). Note that this rounding mode never increases the magnitude of the calculated value.

FLOOR
Rounding mode to round towards negative infinity. If the result is positive, behave as for RoundingMode.DOWN; if negative, behave as for RoundingMode.UP. Note that this rounding mode never increases the calculated value.

Java 除法运算符由 JLS §15.17.2. Division Operator /:

定义

Integer division rounds toward 0.

这就是 5 / -3 结果为 -1 的原因。


您还可以在 Wikipedia 上查看“Truncate”与“Floor”的定义:

There are many ways of rounding a number y to an integer q The most common ones are:

  • round down (or take the floor, or round towards minus infinity): q is the largest integer that does not exceed y.

  • round up (or take the ceiling, or round towards plus infinity): q is the smallest integer that is not less than y.

  • round towards zero (or truncate, or round away from infinity): q is the integer part of y, without its fraction digits.

  • round away from zero (or round towards infinity): if y is an integer, q is y; else q is the integer that is closest to 0 and is such that y is between 0 and q.

  • round to nearest: q is the integer that is closest to y (see below for tie-breaking rules).

如您所见,Java 和维基百科同意这个定义:

  • 截断: 向零舍入
  • 底数: 向 minus/negative 无穷大舍入

请注意 Java 和维基百科对 舍入 的含义存在分歧。