gpt4 book ai didi

swift 3 : How to Calculate Random Number with Favor Towards A Bias

转载 作者:搜寻专家 更新时间:2023-10-31 22:01:32 24 4
gpt4 key购买 nike

假设我正在计算 1 到 100 之间的随机数。我希望它选择的数字是随机的,但我可以设置一个更有可能选择中心的位置。因此,如果我做随机样本让我们说一千次,那么中心数字被更频繁地选择会有明显的相关性。它选择中心的数量应该基于我可以在 didHitChanceOf 函数中设置的数字。执行此操作的最佳方法是什么?

我目前的代码没有做到这一点,甚至是随机性的

当前无偏随机数代码(Swift 3)

extension Int
{
static func random(range: ClosedRange<Int> ) -> Int
{
var offset = 0

if range.lowerBound < 0 // allow negative ranges
{
offset = abs(range.lowerBound)
}

let mini = UInt32(range.lowerBound + offset)
let maxi = UInt32(range.upperBound + offset)

return Int(mini + arc4random_uniform(maxi - mini)) - offset
}
}

func didHitChanceOf(chance: Double) -> Bool{
let random = Int.random(range: 0...100)
if(Double(random) < chance){ //If the conversion rate is 20%, then only 20% of the time will the random number be less than the conversion rate.
return true
}else{
return false
}
}
var adwordsClicks = 500
let adwordsConversionRate = 20
var adwordsConversions = 0
for _ in 0...adwordsClicks {
if(didHitChanceOf(chance: adwordsConversionRate) == true){
adwordsConversions = adwordsConversions + 1
}
}

最佳答案

您可以使用 GameKit 中的 GKGaussianDistribution(又名正态分布)来执行此操作。您将需要 2 个参数:mean(您想要的“中心”)和 deviation(它应该从中心传播多远):

import GameKit

func random(count: Int, in range: ClosedRange<Int>, mean: Int, deviation: Int) -> [Int] {
guard count > 0 else { return [] }

let randomSource = GKARC4RandomSource()
let randomDistribution = GKGaussianDistribution(randomSource: randomSource, mean: Float(mean), deviation: Float(deviation))

// Clamp the result to within the specified range
return (0..<count).map { _ in
let rnd = randomDistribution.nextInt()

if rnd < range.lowerBound {
return range.lowerBound
} else if rnd > range.upperBound {
return range.upperBound
} else {
return rnd
}
}
}

使用和测试:

let arr = random(count: 1_000_000, in: 0...100, mean: 70, deviation: 10)

let summary = NSCountedSet(array: arr)
for i in 0...100 {
print("\(i): \(summary.count(for: i))")
}

您可以看到 70 左右的值的计数最高

关于 swift 3 : How to Calculate Random Number with Favor Towards A Bias,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44534943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com