random ()

doc

Registered
after getting the answer my problem might well become a stupid one ;)

i am programming some c code and need to generate hundrets of random numbers. as i broused the web i consider the random() function best for osx (fast and nearly true random, isnt it?). surely ill randomiz the seed unsing srandom(time(NULL)) on startup.
Apple quotes random() will give me an uniformly distributed set of numbers inbetween -32767 and 32767. As far as good... but. On a bit-related point of view it doesnt make any sens to me. the total number of possible results is 2^16-1. A unusable amount. Its uneven; calculating a large amount of yes-or-no states [e.g. trueOrFalse = (short) (random()+32767)/31767; ] would differ by one every 65535th time). Not only that, i fear random() generates halve of a unsigned short (2^15) and randomly adds the sign. well, would it do so, there would be a +0 and a -0, means the distribution wouldnt be uniformly at all.
The longer i write the more i get suspicious. Maybe i messed it up while i randomized my brain. Maybe all whats unlogical to me is logical to others :)
sorry for beeing discursive once again... but thanks for ideas.
doc
 
Signed data types in C use the twos complement format. That means that there will never be +0 and -0. There isn't a sign bit per se. Roughly speaking, to convert a positive number in twos complement, flip all the bits and add 1.

So as an example and 8 bit 0 is represented as 00000000. To get negative zero, the first step is to flip all the bits, giving you 11111111. Adding 1 to that will give you 00000000. Which shows that with twos complement, -0 and +0 are equal.

If you want to get a random number that's either true or false use the following code:
Code:
int trueOrFalse = rand()  % 2;

use the modulus operator. The code above is the standard way of generating random numbers and will give you a number that's either 0 or 1 which represent true or false. it's better than your other code, as I don't think the random number generator you posted will work the way you expect it to.
 
Thank u all. Guess i got most of what i need. i really dont wanna troll the topic... but.
Made me familiar with the twos complement principles, so the zero cant annihilate the missed number. Yet im still woundering where random looses the last 'number'. i still would expect an amount of 2^16 randomized numbers, especially when all 16 bits should be given in a randomized fashion. so there also should be the number 1000.0000.0000.0000 which must be equal to -32768.
 
Back
Top