Beginner
Beginner

Reputation: 67

(-1)^k with random k of either 0 or 1

I want to have something to happen when (-1)^k is 1 and when its -1 -> k is generated randomly.

I tried this but it doesnt work

let test:Int32 = -1
let leftOrRight:CGFloat = pow(CGFloat(test),random(min:0,max:1))

func random(min : CGFloat, max : CGFloat) -> CGFloat{
    return random() * (max - min) + min
}

leftOrRight is always NaN.

Upvotes: 0

Views: 70

Answers (2)

ielyamani
ielyamani

Reputation: 18591

If you are using Swift 4/4.1 then this should do the trick:

let leftOrRight = 2 * (Double(arc4random_uniform(2)) - 0.5)

If you are using Swift 4.2, you could use:

let array: [CGFloat] = [-1, 1]
let leftOrRight: CGFloat = array.randomElement()

If you want leftOrRightto be a random Boolean:

let leftOrRight: Bool = Bool.random()

For more on what's coming in Swift 4.2 have a look here.

Upvotes: 2

vacawama
vacawama

Reputation: 154681

You are trying to generate a CGFloat value of -1.0 or 1.0 with equal probability. You can do that by generating a value of 0 or 1 (using arc4random_uniform(2)) and testing it before assigning the CGFloat value:

let leftOrRight: CGFloat = arc4random_uniform(2) == 0 ? 1 : -1

In Swift 4.2 (Xcode 10), you could use Bool.random() to simplify it:

let leftOrRight: CGFloat = Bool.random() ? 1 : -1

Upvotes: 5

Related Questions