let num = 32.0
Double(num).remainder(dividingBy: 12.0)
I'm getting -4?..instead of 8.0...it's subtracting 12.0 from 8.0
how do i fix this?
let num = 32.0
Double(num).remainder(dividingBy: 12.0)
I'm getting -4?..instead of 8.0...it's subtracting 12.0 from 8.0
how do i fix this?
Please, read the documentation carefully:
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.
(emphasis mine)
You want to use truncatingRemainder(dividingBy:) instead:
let num = 32.0
let value = Double(num)
.truncatingRemainder(dividingBy: 12)
print(value) // 8
remainder(dividingBy:)
is not the modulus function.
In real division 32.0/12.0 = 2.666666...
. The remainder(dividingBy:) function defines the nearest integer to that result as q
: in this case 3
. So we write:
32.O = q * 12 + r
With q
being an integer, and r
a Double.
32.0 = 3 * 12.0 + r ⇒ r = - 4.0
The remainder r
, as defined by this function, is -4.0
.