Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Swift中为给定范围内的RN实施PRNG xoshiro256+?_Swift_Algorithm_Math_Random - Fatal编程技术网

在Swift中为给定范围内的RN实施PRNG xoshiro256+?

在Swift中为给定范围内的RN实施PRNG xoshiro256+?,swift,algorithm,math,random,Swift,Algorithm,Math,Random,基于用c编写的源代码: 我试图在Swift中实现xoshiro256+伪随机数生成器PRNG。我需要得到一个点,算法给我一个介于0和1之间的数字,然后我可以乘以给定范围的计数,然后移动该范围内的第一个数字 到目前为止,我已经重写了源代码中列出的内容: func rotl(_ x: UInt64, _ k: Int) -> UInt64 { return (x << k) | (x >> (64 - k)) } // This is the rotating

基于用c编写的源代码:

我试图在Swift中实现xoshiro256+伪随机数生成器PRNG。我需要得到一个点,算法给我一个介于0和1之间的数字,然后我可以乘以给定范围的计数,然后移动该范围内的第一个数字

到目前为止,我已经重写了源代码中列出的内容:

func rotl(_ x: UInt64, _ k: Int) -> UInt64 {
    return (x << k) | (x >> (64 - k))
} // This is the rotating function.

var s: [UInt64] = [1,2,3,4] // I gave a seed vector of the basic 1234.

func next() -> UInt64 {
    let result_plus = s[0] + s[3]

    let t = s[1] << 17

    s[2] ^= s[0]
    s[3] ^= s[1]
    s[1] ^= s[2]
    s[0] ^= s[3]

    s[2] ^= t

    s[3] = rotl(s[3], 45)

    return result_plus

} // This returns the next number in the algorithm while XORing the seed vectors for use in the next call.
但是在调用下一个函数6次之后,我得到了一个错误,我猜是因为超过了UInt64的最大限制。这只是猜测


从现在开始,我将如何着手实现我所追求的目标?我猜我需要舍弃低位,以便能够在不超过UInt64的情况下继续调用下一个函数,并且从那里我需要以某种方式转换为double?实际上我在这一点上迷路了。

XOR不能溢出,所以您的问题是加法。将let result_plus=s[0]+s[3]更改为让result_plus=s[0]&+s[3]注意“&”,告诉Swift您希望在溢出时截断加法。您可以阅读苹果《Swift编程语言》一书中有关“溢出运算符”的部分,了解更多详细信息

要转换为双重用途:


Double有52个尾数位,十六进制值为2**52。这将使用UInt64的高52位产生范围内的结果[0,1.0,具有最高可实现的精度。

谢谢!显然C会自动溢出,我不知道;因此这实际上是算法中的目标。你知道我如何转换为0到1之间的数字吗?我想转换为双精度,然后除以双精度64.max?
Double(next() >> 12) / 0x10000000000000