[Subject Prev][Subject Next][Thread Prev][Thread Next][Subject Index][Thread Index]

Re: Why am I not getting the results I expect...



Hi,

Sudhakar Chandra typed:
> display_article_number = 1 + (int) (((float) num_of_arts) * random() /
> (RAND_MAX+1.0));

The only random number > 24 that you seem to get with this code is 25.
When random() becomes very near RAND_MAX it seems to return 25. (Try
substituting RAND_MAX for random() ). Most likely the problem is the
lack of precision of float. Change float to double and things seem to
work fine.

But this algorithm will get slower and slower as you get to the last
few random numbers. A better way to do the task would be:

#include <stdio.h>
#include <stdlib.h>

int main()
{
        int num_of_arts,i,size_of_array;
        int display_article_number;
        int * article_displayed;

        num_of_arts=24;

        article_displayed= (int *) malloc(num_of_arts*sizeof(int));

        for (i=0;i<24;i++) article_displayed[i]=i+1;

        /* Fill the array with numbers from 1 to 24 */

        size_of_array=24; /* The number of remaining random numbers
                             yet to be chosen */
        do
        {
                display_article_number = (int) (((double)
                                size_of_array) * random() / (RAND_MAX+1.0));
                /* Select a random number from 0 to size_of_array-1 */

                printf("%d\n",article_displayed[display_article_number]);
                /* Print the number in the array at that index */

                article_displayed[display_article_number]=
                        article_displayed[--size_of_array];
                /* Now decrement size_of_array and move the last
                 * element of the array to the position already
                 * printed */
        }
        while (size_of_array);
}

I hope it is self-explanatory! ;-) (Thanks to my dad for the above
algorithm and for pointing out the inaccuracy of float)

-- 
Mrinal Kalakrishnan <mrinal@xxxxxxxxx> http://mrinal.dhs.org/
Linux 2.2.16 || PGP:B1E86F5B || Mutt 1.3.4i (2000-06-19) || VIM 5.6 
-- 
quit   When the quit statement is read, the  bc  processor
       is  terminated, regardless of where the quit state-
       ment is found.  For example, "if  (0  ==  1)  quit"
       will cause bc to terminate.
(Seen in the manpage for "bc". Note the "if" statement's logic)