Can rand () really be this bad?

lol

Above is an example of an image generated using rand () to get random coordinates and add a constant to the pixel value in those coordinates. It looks like a few thousand iterations. I use rand () from stdlib.h on Mac OS X Lion, giving it time (NULL) as a seed.

You can clearly see the vertical lines, as if those with an odd x coordinate had higher values ​​than those with an even x coordinate.

How do I implement a better algorithm, or where can I find one that doesn't have many dependencies? (I would prefer the file for header only).

Here is the code (sorry, it took me so long):

void generate(int iterations = 1) { for (unsigned int x = 0;x < (area * 4);++x) { map[rand() % area] += 1; } number a = min(); number b = max(); for (int i = 0;i < area;++i) { map[i] -= a; map[i] /= b; } } 

The map contains double floats and is later converted to RGB values.

+6
source share
4 answers

Have you tried arc4random() ? It provides much stronger and more uniform random values ​​than rand() .

You can also try SecRandomCopyBytes() , which is part of Security.framework. This is basically just read from / dev / random.

+3
source

C ++ 11 provides some pretty useful random number functions in random . See here and here for more details.

+4
source

I think it would be very important to see how you use rand() to retrieve the coordinates. What is really surprising is that you only see the pattern in x coordinates, but not in y. If there really was a flaw in rand() , it should appear in both.

However, I could try to guess where these patterns came from: rand() , as you know, creates more randomness in high bits than in low bits. Therefore, you should never use modulo to extract a smaller range, because this way you can get only low-bit parts with less randomness.

From this knowledge, I would suggest that you extract the low bits to get the x values ​​and high bits to extract the y values. This will give you a much more random pattern along the y axis than along the x axis.

If this is what you are doing, there should be some kind of artifact in your code that causes more randomness along the y axis than along the x axis. Therefore, without seeing your code, it is difficult to say whether this implementation is erroneous.

+3
source

On a poppy, you can just use random instead of rand. The manual page for random notes the following:

ERRORS

About 2/3 speed rand (3).

The historical realization had very little sowing; the random sequence did not differ much from the seed. The current implementation uses the best pseudo random number generator to calculate the initial state.

Applications requiring cryptographic qualitative randomness should use arc4random (3).

+1
source

Source: https://habr.com/ru/post/916302/


All Articles