Search code examples
swiftarc4random

Using arc4random_uniform to return a both whole and non whole doubles


Using Swift, I am trying to figure out how to use arc4random_uniform to return a number like 37.7. The guidance I must abide by is I must do it in a function, the random double must be between 0 - 300. I have been able to build a function that randomly returns doubles between the range but can't find anything that will lead me to outputting random non whole numbers

//function to randomly generate a double number like 105.3
func makeRandDbl() -> Double {
    let randGenerator: Double = Double(arc4random_uniform(301))
    print(randGenerator)

return randGenerator
}

makeRandDb()

Solution

  • To generate a Double in the range 0.0 to 300.0 (with one digit following the decimal):

    Double(arc4random_uniform(3001))/10.0
    

    You can extend this to more decimal places. For two decimal places (0.00 to 300.00):

    Double(arc4random_uniform(30001))/100.0
    

    For three decimal places (0.000 to 300.000):

    Double(arc4random_uniform(300001))/1000.0
    

    This has the advantage of being able to actually generate whole values. In the first case 10% of the numbers will be whole. In the second case 1% of the numbers will be whole. And in the third, 0.1% of the numbers will be whole.