Sender: crough45 AT amc DOT de Message-Id: <97Jun5.143235gmt+0100.16652@internet01.amc.de> Date: Thu, 5 Jun 1997 13:36:05 +0100 From: Chris Croughton Mime-Version: 1.0 To: deef AT pobox DOT oleane DOT com Cc: djgpp AT delorie DOT com Subject: Re: Random numbers/George Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Precedence: bulk Francois Charton wrote: > This is not the case with the rand() function from DJGPP > libc, but it may exist for other rand() functions. The DJGPP one is better than most (you're correct, it does avoid the odd/even trap) but as you say it's not portably true, and it does still have more randomness in some bits than in others. > For this reason, I think it is always bad programming > practice to use (rand()%n), the good way to do it is > (rand()/(MAXRAND/n)), MAXRAND being the largest number > rand() can produce (the modulus in the case of a linear > congruential generator). As pointed out before, that will sometimes generate numbers outside your range due to rounding. For instance: max. random value M = 65535 range of numbers n = 10 M/n = 6553 65535 / 6553 = 10 so it can sometimes generate the number 10 which is outside the range 0-9. That's fine if you combine it with George's algorithm (generata another number if the result is outside the wanted range), but not on its own. OK, it's only (in the above case) 5 out of 65536 times, but if you're using it to index an array you can guarantee those cases will occur and cause a SEGV at exactly the wrong time. Chris C