Answers for "What algorithm does RAND() in SQL Server use?"
https://ask.sqlservercentral.com/questions/2981/what-algorithm-does-rand-in-sql-server-use.html
The latest answers for the question "What algorithm does RAND() in SQL Server use?"Answer by paganaye
https://ask.sqlservercentral.com/answers/86088/view.html
Here is my attempt to guessing the Algorithm used in SQL Rand()
This algorithm returns the same value than SQL on my machine.
Let me know if this works with you.
This is C# code.
public class SQLRand
{
private static int n1;
private static int n2;
#region "PRIVATE METHODS"
private static void ShiftAndCarry(ref int n, int LEQA, Int64 MULTIPLIER, int SHIFT, int MODULUS)
{
n = n * LEQA - ((int)(n * MULTIPLIER >> SHIFT)) * MODULUS;
if (n < 0) n += MODULUS;
}
private static int IntRand()
{
ShiftAndCarry(ref n1,
LEQA: 40014,
MULTIPLIER: 327796565,
SHIFT: 44,
MODULUS: 2147483563); // The 105,097,561st prime
ShiftAndCarry(ref n2,
LEQA: 40692,
MULTIPLIER: 1333397965,
SHIFT: 46,
MODULUS: 2147483399); // the 105,097,554th prime
// We used two of the bigger prime that would fit a C# integer.
// The biggest prime number that would fit is int.MaxValue = 2^31 - 1 = 2,147,483,647 (the 105,097,565th prime)
int result = n1 - n2;
if (result < 1) result += (2147483563 - 1); // same modulo than for n1
return result;
}
#endregion "PRIVATE METHODS"
/// <summary>
/// Returns a pseudo-random number.
/// </summary>
/// <returns>double value from 0 through 1, exclusive</returns>
public static double Rand()
{
const double RAND_DIVIDER = 2147483589.4672801884116202;
return IntRand() / RAND_DIVIDER;
}
/// <summary>
/// Initiate the pseudo-random number generator using a seed, and return a 'not-so-random' first value.
/// </summary>
/// <param name="seed">Seed is an integer that fixes the returned value and subsquent calls.</param>
/// <returns>double value from 0 through 1, exclusive</returns>
public static double Rand(int seed)
{
n1 = (seed < 0 ? -seed : seed == 0 ? 12345 : seed);
n2 = 67890;
return Rand();
}
}Wed, 01 Feb 2012 11:26:14 GMTpaganayeAnswer by Peso
https://ask.sqlservercentral.com/answers/2995/view.html
<p>I wouldn't use RAND. Nowadays I use ABS(CHECKSUM(NEWID())) % 1000 to get random number between 0 and 999. It has better distribution than RAND().
Also RAND() alwasys returns same value first time after SQL Server restart, if I remember correctly.</p>Fri, 13 Nov 2009 16:48:39 GMTPeso