jeudi 1 décembre 2016

Explanation for interesting phenomenom with Random() and colors

Ok, a student of mine had a cool result which I just couldn't explain. In her code, she wants to create random circles (in WPF) with Random colors. She made the typical beginner's mistake of creating more than one Random generator, but bare with me, please.

This is the code:

        Random cir = new Random();
        Random color = new Random();

        for (i = 0; i < 100; i++)
        {
            int r = cir.Next(0, 50);
            diameter = r * 2;
            int posx = cir.Next(0, (510 - diameter));
            int posy = cir.Next(0, (280 - diameter ));


            byte c1 = (byte)color.Next(255);
            byte c2 = (byte)color.Next(255);
            byte c3 = (byte)color.Next(255);
            SolidColorBrush usedcolor = new SolidColorBrush(Color.FromRgb(c1,c2,c3

               ));
            Ellipse circle = new Ellipse();
            circle.Height = diameter;
            circle.Width = diameter;
            circle.Margin = new Thickness(posx, posy, 0, 0);
            circle.Stroke = usedcolor;
            // melkweg.StrokeThickness = dikte;

            Ruimte.Children.Add(circle);
        }

This will always generate the same effect: the colors appear to be 'grouped' , you'll always get the same colors in the same region. Two examples: enter image description here

I understand that the two Random generators are created at the quasi-exact same moment and so have the same seed and are basically 'in sync'. However, since we demand different ranges every Next I was thinking this would result in non-correlated numbers, but I am clearly wrong. (has the Range no impact? Does Random.Next just always generates a number between 0 and 1 and then expands it (denormalise?) it to the desired range? )

Even by simply calling one more Next() on cir or color (e.g. color.Next(1);) will generate a completely random figure as desired, and not the cool, but unwanted effect.

Hope this explanation is full and someone can help me out. Thanks a bunch!




Aucun commentaire:

Enregistrer un commentaire