Swift Random Float Between 0 and 1

Swift random float between 0 and 1

Try initializing the divisor as a float as well, a la:

CGFloat(Float(arc4random()) / Float(UINT32_MAX))

Generate a random float between 0 and 1

Random value in [0, 1[ (including 0, excluding 1):

double val = ((double)arc4random() / UINT32_MAX);

A bit more details here.

Actual range is [0, 0.999999999767169356], as upper bound is (double)0xFFFFFFFF / 0x100000000.

How to make random float in swift with math operations

var red1 = Float((random()%9)*30)/255

You don't need the semicolon and red1 will be type inferred to a Float.

In swift 4.2: var red1 = Float.random(in: startNumber...endNumber)

How does one generate a random number in Swift?

Swift 4.2+

Swift 4.2 shipped with Xcode 10 introduces new easy-to-use random functions for many data types.
You can call the random() method on numeric types.

let randomInt = Int.random(in: 0..<6)
let randomDouble = Double.random(in: 2.71828...3.14159)
let randomBool = Bool.random()

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

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.

get round numbers between 0 to 1

  • Multiply by 10 to get values between 0.0 and 10.0
  • round to remove the decimal
  • divide by 10

Example:

let values = [0, 0.0643739, 0.590829, 0.72273, 1]

for value in values {
print("\(value) -> \(round(value * 10) / 10)")
}

// 0.0 -> 0.0
// 0.0643739 -> 0.1
// 0.590829 -> 0.6
// 0.72273 -> 0.7
// 1.0 -> 1.0


Related Topics



Leave a reply



Submit