From owner-freebsd-stable@FreeBSD.ORG Mon Apr 7 07:16:08 2003 Return-Path: Delivered-To: freebsd-stable@freebsd.org Received: from mx1.FreeBSD.org (mx1.freebsd.org [216.136.204.125]) by hub.freebsd.org (Postfix) with ESMTP id C5B7137B401 for ; Mon, 7 Apr 2003 07:16:08 -0700 (PDT) Received: from salmon.maths.tcd.ie (salmon.maths.tcd.ie [134.226.81.11]) by mx1.FreeBSD.org (Postfix) with SMTP id 4558F43F85 for ; Mon, 7 Apr 2003 07:16:07 -0700 (PDT) (envelope-from dwmalone@maths.tcd.ie) Received: from walton.maths.tcd.ie by salmon.maths.tcd.ie with SMTP id ; 7 Apr 2003 15:16:06 +0100 (BST) Date: Mon, 7 Apr 2003 15:16:03 +0100 From: David Malone To: Eric Timme Message-ID: <20030407141603.GA96746@walton.maths.tcd.ie> References: <200304070901.20557.timothy@voidnet.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <200304070901.20557.timothy@voidnet.com> User-Agent: Mutt/1.5.3i Sender: dwmalone@maths.tcd.ie cc: freebsd-stable@freebsd.org Subject: Re: 4-stable and C rand()? X-BeenThere: freebsd-stable@freebsd.org X-Mailman-Version: 2.1.1 Precedence: list List-Id: Production branch of FreeBSD source code List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Mon, 07 Apr 2003 14:16:09 -0000 On Mon, Apr 07, 2003 at 09:01:20AM -0500, Eric Timme wrote: > No matter how many times I run this it seems to alternate between generating > two different but non-unique sets of values, depending on whether time(0) is > even or odd..and I can't understand why (values at the end of this message). In each case you are only looking at the low order bits of the number, which will always be particularly bad. The simple linear congruence generators used for rand have the form: seed = seed * 1103515245 + 12345 return seed % (RAND_MAX+1) where RAND_MAX+1 is a power of two. Since you're looking at this mod 32 (and mod 4) it becomes somthing like: seed = seed * 13 + 25 return seed % 32 where seed is effectively now a number between 0 and 31. This can't have a period of longer than 32 calls. Rather than use rand()%32 you might want to use something like (rand()+RAND_MAX/64)/(RAND_MAX/32) - using the high order bits means that you are not effectively reducing the side of the state space. David.