Jonnyr612
Jonnyr612

Reputation: 217

How to generate a Random Floating point Number in range, Swift

I'm fairly new to Swift, only having used Python and Pascal before. I was wondering if anyone could help with generating a floating point number in range. I know that cannot be done straight up. So this is what I've created. However, it doesn't seem to work.

func location() {
    // let DivisionConstant = UInt32(1000)

    let randomIntHeight = arc4random_uniform(1000000) + 12340000
    let randomIntWidth = arc4random_uniform(1000000) + 7500000

    XRandomFloat = Float(randomIntHeight / UInt32(10000))
    YRandomFloat = Float(randomIntWidth / UInt32(10000))

    randomXFloat = CGFloat(XRandomFloat)
    randomYFloat = CGFloat(YRandomFloat)

    self.Item.center = CGPointMake(randomXFloat, randomYFloat)
}

By the looks of it, when I run it, it is not dividing by the value of the DivisionConstant, so I commented this and replaced it with a raw value. However, self.Item still appears off screen. Any advice would be greatly appreciated.

Upvotes: 1

Views: 1813

Answers (2)

Rob Napier
Rob Napier

Reputation: 299485

This division probably isn't what you intended:

XRandomFloat = Float(randomIntHeight / UInt32(10000))

This performs integer division (discarding any remainder) and then converts the result to Float. What you probably meant was:

XRandomFloat = Float(randomIntHeight) / Float(10000)

This is a floating point number with a granularity of approximately 1/10000.

Your initial code:

let randomIntHeight = arc4random_uniform(1000000) + 12340000

generates a random number between 12340000 and (12340000+1000000-1). Given your final scaling, that means a range of 1234 and 1333. This seems odd for your final goals. I assume you really meant just arc4random_uniform(12340000), but I may misunderstand your goal.


Given your comments, I think you've over-complicated this. The following should give you a random point on the screen, assuming you want an integral (i.e. non-fractional) point, which is almost always what you'd want:

let bounds = UIScreen.mainScreen().bounds

let x = arc4random_uniform(UInt32(bounds.width))
let y = arc4random_uniform(UInt32(bounds.height))
let randomPoint = CGPoint(x: CGFloat(x), y: CGFloat(y))

Your problem is that you're adding the the maximum value to your random value, so of course it's always going to be offscreen.

Upvotes: 1

Tom Harrington
Tom Harrington

Reputation: 70966

I'm not sure what numbers you're hoping to generate, but what you're getting are results like:

1317.0, 764.0
1237.0, 795.0
1320.0, 814.0
1275.0, 794.0
1314.0, 758.0
1300.0, 758.0
1260.0, 809.0
1279.0, 768.0
1315.0, 838.0
1284.0, 763.0
1273.0, 828.0
1263.0, 770.0
1252.0, 776.0
1255.0, 848.0
1277.0, 847.0
1236.0, 847.0
1320.0, 772.0
1268.0, 759.0

You're then using this as the center of a UI element. Unless it's very large, it's likely to be off-screen.

Upvotes: 0

Related Questions