I want to generate a random double between 0 and 5. I am doing
Double.random(in: 0.0…5.0)
In playground or debugging I get a very nice unified distribution. In the appstore so far after 100 draws the highest number I got was 0.59. Seems highly unlikely that it will suddenly draw higher numbers than that.
Anyone might know a reason for this not-so-random draw? and is there a better way to get a random double that will more random than this?
CodePudding user response:
The function Double.random(in: 0.0...5.0)
seems fine and working on me when I try it on my playground, but if there's problem generating random double, try generating a random Int instead.
func randomDoubleFromInt() -> Double {
let n1 = Int.random(in: 0...5)
let n2 = Int.random(in: 0...9999999999)
let nStr = "\(n1).\(n2)"
return Double(nStr)!
}
CodePudding user response:
I could not replicate your issue. Here is the test code I used, it gives a wide range of numbers between 0.0 and 5.0. On macos 12.2-beta, using xcode 13.2, targets ios 15 and macCatalyst 12.
import SwiftUI
import Foundation
@main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
var body: some View {
Text("tesing")
.onAppear {
for i in 0...100 {
let x = drand48() * 5.0 // <-- alternative
// let x = Double.random(in: 0.0 ... 5.0)
print("---> \(i) => \(x)")
}
}
}
}