0

I'm trying to generate random double numbers between 0 and 1 but I'm getting always 0

func randFunct() -> Double {
     let randomInt = arc4random_uniform(100) + 1 // [1, 100]
     let randomDouble : Double = Double(randomInt/100)
     return randomDouble
}
Developer2012
  • 169
  • 2
  • 13

2 Answers2

3

Try this:

extension Double {
    private static let arc4randomMax = Double(UInt32.max)

    static func random0to1() -> Double {
         return Double(arc4random()) / arc4randomMax
    }
}

print(Double.random0to1())
Alexander
  • 59,041
  • 12
  • 98
  • 151
-1

It solves my question:

    let randomDouble : Double = Double(arc4random()) / Double(UINT32_MAX) * abs(0 - 1) + min(0, 1)
Developer2012
  • 169
  • 2
  • 13
  • 2
    You can keep your original code, just change the parenthesis to make it a Double before dividing by 100. BTW if you want a number from 0.0 to 1.0 just use arc4random_uniform(101) that would generate a number between 0-100. `var randomDouble: Double { return Double(arc4random_uniform(101))/100 }` – Leo Dabus Aug 26 '16 at 18:31
  • 1
    `* abs(0 - 1) + min(0, 1)`? – Hamish Aug 26 '16 at 19:02
  • @Hamish == `* -1 + 0` == `* -1`? Yeah I'm confused, too. :p – Alexander Aug 26 '16 at 19:45
  • @AlexanderMomchliov Equals `* 1 + 0`... so just plain useless lol :P – Hamish Aug 26 '16 at 19:46
  • 1
    Ah yeah, it does an abs on the `-1`. lol I'm more confused now. – Alexander Aug 26 '16 at 19:48