Java,找到 182.5 % (365 / 12)

Java, find 182.5 % (365 / 12)

我想使用 Java 求商和余数,但在涉及重复小数时遇到困难。

以下列等式为例(用Google计算器测试):

division: 182.5 / (365 / 12) = 6
remainder: 182.5 % (365 / 12) = 0

现在,Java中的一个简单测试:

System.out.println("division: " + 182.5 / (365.0 / 12));
System.out.println("remainder: " + 182.5 % (365.0 / 12));

输出:

division: 6.000
remainder: 30.415

我知道 double 有局限性,所以我尝试使用 BigDecimal:

BigDecimal daysInYear = new BigDecimal("365");
BigDecimal monthsInYear = new BigDecimal("12");
BigDecimal daysInMonth = daysInYear.divide(monthsInYear, 3, RoundingMode.CEILING);
BigDecimal daysInHalfYear = new BigDecimal("182.5");
BigDecimal division = daysInHalfYear.divide(daysInMonth, 3, RoundingMode.CEILING);
BigDecimal remainder = daysInHalfYear.remainder(daysInMonth);
System.out.println("division: " + division);
System.out.println("remainder: " + remainder);

输出:

division: 6.0
remainder: 30.41666666666666

我需要做什么才能得到以下结果?

182.5 % (365 / 12) = 0

有许多编程语言原生支持对有理数的精确运算。 Java 不是其中之一。通常这不是一个大问题,因为 double 的精度对于大多数应用程序来说已经足够了。余数是一种边缘情况,在这种情况下,非常小的舍入误差可能会导致较大的意外结果。

您的选择是:

  1. 使用不同的语言
  2. 使用支持有理数的库(例如Rational
  3. 写你自己的 Rational class
  4. 利用数学重做您的操作x % (y / z) => (x * z % y) / z