gpt4 book ai didi

swift4 - 如何在 Swift 4 中从正态分布返回 float 或 double ?

转载 作者:行者123 更新时间:2023-12-05 01:00:28 24 4
gpt4 key购买 nike

我试图从 Swift4 中的平均值 = 0 和标准差 = 4 的正态分布返回 float 或 double 。最接近我需要的方法是使用 GameplayKit -> GKGaussianDistribution,如以下代码所示:

func generateForecast() {
let gauss = GKGaussianDistribution(randomSource: self.source, mean: 0.0, deviation: 4.0)
self.epsilon = gauss.nextInt()
}

我的问题是当我打电话时

gauss.nextInt()

我显然得到一个整数。当我尝试

gauss.nextUniform()

我得到一个介于 -1 和 1 之间的数字。

有没有一种相当简单的方法可以从 Swift4 中的正态分布返回 float 或 double ,而不是 Int 或 -1 和 1 之间的 float ?

import AppKit
import PlaygroundSupport
import GameplayKit

let nibFile = NSNib.Name(rawValue:"MyView")
var topLevelObjects : NSArray?

Bundle.main.loadNibNamed(nibFile, owner:nil, topLevelObjects: &topLevelObjects)
let views = (topLevelObjects as! Array<Any>).filter { $0 is NSView }

// Present the view in Playground
PlaygroundPage.current.liveView = views[0] as! NSView

let s = 0.001
var auto_corr: [Int] = []

class Market {
var numAgents: Int
var traders: [Agent] = []
var price: Double
var epsilon: Int
var priceHist: [Double] = []
var returnHist: [Double] = []
var returnRealHist: [Double] = []
var logReturn: Double = 0
var realReturn: Double = 0
let source = GKRandomSource()

init(numAgents: Int, price: Double, epsilon: Int) {
self.numAgents = numAgents
self.price = price
self.epsilon = epsilon
for _ in 1...numAgents {
self.traders.append(Agent(phi: 1, theta: 1))
}
}

func generateForecast() {
let gauss = GKGaussianDistribution(randomSource: self.source, mean: 0.0, deviation: 4.0)
self.epsilon = gauss.nextInt()
}

}

最佳答案

GKGaussianDistribution 的文档没有提到它覆盖了基类中的 nextUniform() 所以不要假设它会为你返回正态分布的值:

您可以使用 Box-Muller Transformation 滚动您自己的高斯分布:

class MyGaussianDistribution {
private let randomSource: GKRandomSource
let mean: Float
let deviation: Float

init(randomSource: GKRandomSource, mean: Float, deviation: Float) {
precondition(deviation >= 0)
self.randomSource = randomSource
self.mean = mean
self.deviation = deviation
}

func nextFloat() -> Float {
guard deviation > 0 else { return mean }

let x1 = randomSource.nextUniform() // a random number between 0 and 1
let x2 = randomSource.nextUniform() // a random number between 0 and 1
let z1 = sqrt(-2 * log(x1)) * cos(2 * Float.pi * x2) // z1 is normally distributed

// Convert z1 from the Standard Normal Distribution to our Normal Distribution
return z1 * deviation + mean
}
}

我故意没有从 GKRandomDistribution 子类化它,因为还有其他方法我需要覆盖但与这个问题无关。

关于swift4 - 如何在 Swift 4 中从正态分布返回 float 或 double ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49470358/

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