I understand that arc4random returns an unsigned integer up to (2^32)-1. In this scenario it it always gives a number between 0 and 1.
var x:UInt32 = (arc4random() / 0xFFFFFFFF)
How does the division by 0xFFFFFFFF cause the number to be between 0 - 1?
As you've stated,
arc4random returns an unsigned integer up to (2^32)-1
0xFFFFFFFF is equal to (2^32)-1, which is the largest possible value of arc4random()
. So the arithmetic expression (arc4random() / 0xFFFFFFFF)
gives you a ratio that is always between 0 and 1 — and as this is an integer division, the result can only be between 0 and 1.
to receive value between 0 and 1, the result must be floating point value
import Foundation
(1..<10).forEach { _ in
let x: Double = (Double(arc4random()) / 0xFFFFFFFF)
print(x)
}
/*
0.909680047749933
0.539794033984606
0.049406117305487
0.644912529188421
0.00758233550181201
0.0036165844657497
0.504160538898818
0.879743074271768
0.980051155663107
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With