Home > database >  Does Swift's Double.random(in: -1...1) return -1 and 1?
Does Swift's Double.random(in: -1...1) return -1 and 1?

Time:08-30

I actually tried to check for myself, but found it impossible because the probability was too small.
I just wanted a clear answer.

var minValue = 0.0
var maxValue = 0.0
for i in 1...Int.max {
    let randomValue = Double.random(in: -1...1)
    minValue = min(minValue, randomValue)
    maxValue = max(maxValue, randomValue)

    if i.isMultiple(of: 1_000_000) {
        print("min, max:", minValue, maxValue)
    }
}

CodePudding user response:

We can see that the answer is "yes" by reading the documentation of random(in:), ClosedRange, and also ClosedRange.contains.

random(in: range) is said to return:

A random value within the bounds of range.

Well, are -1 and 1 "within the bounds of" -1...1? The docs of ClosedRange says "yes":

You create a ClosedRange instance by using the closed range operator (...).

let throughFive = 0...5

A ClosedRange instance contains both its lower bound and its upper bound.

throughFive.contains(3)
// true
throughFive.contains(10)
// false
throughFive.contains(5)
// true

See also the discussion in ClosedRange.contains:

A ClosedRange instance contains both its lower and upper bound. element is contained in the range if it is between the two bounds or equal to either bound.

So theoretically, Double.random(in: -1...1) does have a (very small) chance of returning the bounds of the range, -1 or 1, as they are "within the range".

You can show that the bounds of the range can indeed be returned by random by creating a range such as 1...1 - there is only one element to return!

Double.random(in: 1...1) // will always return 1, which is the bound

CodePudding user response:

Not really an answer but here is a more efficient way to check if the bound (upper in this case) is ever reached

var randomValue = -1.0
for i in 1...Int.max {
    randomValue = Double.random(in: randomValue...1)
    print(randomValue)
    if randomValue == 1 {
        print("limit reached")
        break
    }
}
  • Related