POV-Ray : Newsgroups : povray.general : Random integer : Re: Random integer Server Time
12 Jun 2024 00:28:04 EDT (-0400)
  Re: Random integer  
From: clipka
Date: 5 Feb 2016 02:51:55
Message: <56b4549b$1@news.povray.org>
Am 05.02.2016 um 03:50 schrieb Mike Horvath:
> On 1/31/2016 10:16 PM, clipka wrote:
>> Am 01.02.2016 um 03:10 schrieb clipka:
>>> Am 01.02.2016 um 02:55 schrieb Mike Horvath:
>>>> How do I calculate a random integer between n and p, inclusively?
>>>
>>> floor( rand(R)*((p-n)+1) + 0.5 )
>>>
>>> should do the trick
>>
>> ... provided you figure out that you need to add n ;)
>>
>> Oops.
>>
> 
> Where do I add n?

Never mind -- I also included other nonsense in the formula.

Let me try that again:

    min( n+floor( rand(R)*((p-n)+1) ), p )

The min() is there to ensure that the result is never larger than p,
even if R is so close to 1.0 that the expression in floor() is at some
point rounded up to give a result of (p-n)+1, in which case the entire
expression (without the min()) would result in p+1.

I'm adding n only after rounding, because the lower the magnitude of a
floating point number, the higher its absolute precision.


Post a reply to this message

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