Swift Double.remainder(dividingBy:) 返回负值
Swift Double.remainder(dividingBy:) returning negative value
let num = 32.0
Double(num).remainder(dividingBy: 12.0)
我得到 -4?..而不是 8.0...它是从 8.0 中减去 12.0
我该如何解决这个问题?
请仔细阅读documentation:
For two finite values x and y, the remainder r of dividing x by y satisfies x == y * q + r, where q is the integer nearest to x / y. If x / y is exactly halfway between two integers, q is chosen to be even. Note that q is not x / y computed in floating-point arithmetic, and that q may not be representable in any available integer type.
(强调我的)
您想改用 truncatingRemainder(dividingBy:):
let num = 32.0
let value = Double(num)
.truncatingRemainder(dividingBy: 12)
print(value) // 8
remainder(dividingBy:)
不是取模函数
实数划分32.0/12.0 = 2.666666...
。 remainder(dividingBy:) 函数将最接近该结果的整数定义为 q
:在本例中为 3
。所以我们写:
32.O = q * 12 + r
q
是整数,r
是双精度数。
32.0 = 3 * 12.0 + r ⇒ r = - 4.0
此函数定义的余数 r
为 -4.0
。
let num = 32.0
Double(num).remainder(dividingBy: 12.0)
我得到 -4?..而不是 8.0...它是从 8.0 中减去 12.0
我该如何解决这个问题?
请仔细阅读documentation:
For two finite values x and y, the remainder r of dividing x by y satisfies x == y * q + r, where q is the integer nearest to x / y. If x / y is exactly halfway between two integers, q is chosen to be even. Note that q is not x / y computed in floating-point arithmetic, and that q may not be representable in any available integer type.
(强调我的)
您想改用 truncatingRemainder(dividingBy:):
let num = 32.0
let value = Double(num)
.truncatingRemainder(dividingBy: 12)
print(value) // 8
remainder(dividingBy:)
不是取模函数
实数划分32.0/12.0 = 2.666666...
。 remainder(dividingBy:) 函数将最接近该结果的整数定义为 q
:在本例中为 3
。所以我们写:
32.O = q * 12 + r
q
是整数,r
是双精度数。
32.0 = 3 * 12.0 + r ⇒ r = - 4.0
此函数定义的余数 r
为 -4.0
。