POV-Ray : Newsgroups : povray.programming : random numbers in c++ : Re: random numbers in c++ Server Time
20 Apr 2024 05:46:03 EDT (-0400)
  Re: random numbers in c++  
From: Le Forgeron
Date: 25 Aug 2010 02:51:34
Message: <4c74bd76$1@news.povray.org>
Le 25/08/2010 06:13, Anthony D. Baye a écrit :
> I'm working on an implementation of the Diamond-Square algorithm, and it seems
> to be working... sort of, but for two things.
> 
> First, I'm getting seriously large pixel values.  I've been trying to clamp them
> between 0 and 255 inclusive, but it's not working the way I hoped it would.
> 
> Second my random number function. (I've attached the source file, but I'll
> reiterate the function here) I'm using the rand() function from cstdlib:
> 
> double Random(double r)
> {
>      double rNum;
> 
>      rNum = r - (2*r)/(rand()%65535);
> 
>      return rNum;
> }
> 
> theoretically, this should generate a random number between -r and r, but I'm
> only getting positive values within a small range.  reducing the range of random
> values to 100 or less seems to generate more negative numbers but problems
> persist.

The problem is in your formula:  R - 2R/X with X between 0 & 65534 leads to:
 * a problem with when X== 0
 * -r when X== 1
 * 0 when X== 2
 * a positive value near r when X > 10 (with near ~ within 10%)

I guess you want to fix it.
Also, rand() is weak, why not using drand48() instead ?

   rnum = r*(1.0-2.0*drand48());
/* notice the usage of .0 to force double computation not integer one */

or even better if non portable is not a problem and you are in the gnu
world: the drand48_r version (or at least the rand_r version), so as to
avoid reentrancy issue ? (as long as YOU protect the state)

> 
> At the moment, the largest problem seems to be clamping the values.
> 
> the code outputs the result to a pgm file with a depth of 8 bits
> 
> changing the range multiplier seems to have some interesting effects, but I'm
> not sure I like the results.
> 
> Any help would be appreciated.
> 
> A.D.B.
> 


-- 
Real software engineers work from 9 to 5, because that is<br/>
the way the job is described in the formal spec.  Working<br/>
late would feel like using an undocumented external procedure.


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.