gpt4 book ai didi

C# 随机(长)

转载 作者:太空狗 更新时间:2023-10-29 21:54:36 31 4
gpt4 key购买 nike

我正在尝试基于 C# 中的种子生成一个数字。唯一的问题是种子太大而不能成为 int32。有什么方法可以像种子一样使用 long 吗?

是的,种子必须很长。

最佳答案

这是我移植的 Java.Util.Random 的 C# 版本 from the Java Specification .

最好的办法是编写一个 Java 程序来生成大量数字,并检查此 C# 版本是否生成相同的数字。

public sealed class JavaRng
{
public JavaRng(long seed)
{
_seed = (seed ^ LARGE_PRIME) & ((1L << 48) - 1);
}

public int NextInt(int n)
{
if (n <= 0)
throw new ArgumentOutOfRangeException("n", n, "n must be positive");

if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);

int bits, val;

do
{
bits = next(31);
val = bits % n;
} while (bits - val + (n-1) < 0);
return val;
}

private int next(int bits)
{
_seed = (_seed*LARGE_PRIME + SMALL_PRIME) & ((1L << 48) - 1);
return (int) (((uint)_seed) >> (48 - bits));
}

private long _seed;

private const long LARGE_PRIME = 0x5DEECE66DL;
private const long SMALL_PRIME = 0xBL;
}

关于C# 随机(长),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15463033/

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