Page 1 of 1

rnd()

Posted: Wed Dec 09, 2009 5:58 pm
by y offs et
As I read it "rnd() - returns a random number in the range 0 to 1. "
means -
integers 0 and 1 are possible, as well as fractions between
correct?

Posted: Wed Dec 09, 2009 9:14 pm
by VilleK
The rnd()-function use the built-in Random-function in Delphi which behaves just like the corresponding function in most programming languages. It returns values in the range: 0 <= Number < 1.0

So it can be zero and 0.99999 but never 1.0. If you type: "int x=rnd() * 5;" you will get values between 0 and 4.

http://www.delphibasics.co.uk/RTL.asp?Name=Random

Posted: Wed Dec 09, 2009 10:22 pm
by y offs et
Thanks for link. I've overviewed at least a dozen languages and there is always little differences. I'll clarify the Docs.

"int x=rnd() * 5;"
Small question - if x is already defined as an integer variable, is the "int" required? I've been using x = round(rnd()*5);

Posted: Thu Dec 10, 2009 3:43 pm
by jph_wacheski
So

"int x=rnd() * 5;" you will get values between 0 and 4.9995

correct?

Posted: Thu Dec 10, 2009 4:00 pm
by VilleK
You don't have to redeclare x if it is already defined so "x=" is enough.

float f=rnd() * 5; //Gives a number between 0 and 4.99999...

int x=round(rnd() * 5); //Gives an integer between 0 and 5

int x=rnd() * 5; //Gives an integer between 0 and 4

Round() rounds values to the nearest integer, so 4.6 rounds up to 5. The default number to integer conversion is to truncate the decimals so that 4.7894 becomes 4.

I'm writing from memory and I haven't verified the information above in the editor, but this is how it should work :)

Posted: Thu Dec 10, 2009 7:08 pm
by y offs et
according to the link -

" round(x) - returns the integer part of x " from the Docs is incorrect.

trunc() is the function that produces this

http://www.delphibasics.co.uk/RTL.asp?Name=Trunc

----------------

On checking others, I see you have been inventing some. Hmm... :?

Posted: Thu Dec 10, 2009 9:46 pm
by VilleK
If you find inconsistencies between the wiki and the Delphi-docs then the Delphi-docs are probably more correct.

Posted: Thu Dec 10, 2009 9:55 pm
by y offs et
OK. So that means there is no actual truncation function and I'll have to find another way.

Posted: Thu Dec 10, 2009 10:12 pm
by VilleK
Trunc is basically x-frac(x).