11-16-2022 05:47 AM
Hi,
We have a problem, where Random number generation is jamming if seed is set to 16384 or its multiple (16384,32768,49153,65536 ...).
We are using Random() function to generate the number and SetRandomSeed() to set the seed.
We were originally using the 0 as seed value to get current time as seed and noticed that it freezes every now and then. Then we tried starting from seed value 1 and stepping up one by one and noticed that it freezes the execution always at intervals of 16384?
Using CVI 2015.
What could be causing this kind of problem?
11-16-2022 10:21 AM
Random () and associated functions are part of the Programmer's Toolbox, whose source is distributed: you can find it in C:\Program Files (x86)\National Instruments\CVI2015\toolslib\toolbox folder.
Examining that code you can see that the very first instruction is
pThreadLocalVars->seedX = pThreadLocalVars->randomSeed & 0x3FFF;
Now as it is evident if randomSeed is 0x4000 that line gives 0 which causes the function to fall into while(!pThreadLocalVars->seedX) infinite loop.
An advice should be give into function documentation to avoid numbers with leftmost 14 bits to zero. Returning an error in SetRandomSeed would be even better.
11-16-2022 10:56 AM - edited 11-16-2022 10:59 AM
Thanks for the response! That explains it.
In SetRandomSeed it is also possible to trigger this error when giving 0 as parameter which should be a valid parameter as it will the use current clock value as a random seed.
Maybe in that case the function could check that the seed returned by clock is not a multiple of 16 384 and if it is, wait for the clock value to change to something that is not multiple of 16 384 in order to avoid infinite loop in next call to Random?
#if HAVE_CVI_RTE
void CVIFUNC SetRandomSeed(unsigned long seed)
{
ThreadLocalVars *pThreadLocalVars = 0;
pThreadLocalVars = GetThreadLocalVars();
if (seed)
pThreadLocalVars->randomSeed = seed; /* Multithreaded, each thread has its own thread local seed. */
else
do
{
// If clock return multiple of 16 384 -> infinite loop in next call to Random()
pThreadLocalVars->randomSeed = clock();
} while (!pThreadLocalVars->randomSeed); /* make sure we don't somehow get zero, since that would cause an infinite loop */
pThreadLocalVars->reSeed = TRUE;
}
11-16-2022 03:58 PM
Yes, it's definitely possible to do something like that. You could also modify and recompile the library so that this correction is retained for all of your projects. For such an old version NI is not likely to release a patch fot this or other bugs.
11-17-2022 01:38 AM
An advice should be give into function documentation to avoid numbers withleftmostrightmost 14 bits to zero. Returning an error in SetRandomSeed would be even better.
Just to correct myself...