how to get random nubmer +1 or -1 (just need it for "+" or "-") - objective-c-2.0

i need random number but only +1 or -1 (to have force direction defined in box2d) how to get this only two random numbers? thank you!

int random = arc4rand()%2 ? -1 : 1;

int result = (WhateverRandomNumbersComeFromInObjectiveC() >= 0.5) ? 1 : -1;

#include <stdlib.h>
(arc4random() % 2) * 2 - 1
arc4random() gives a random integer
(arc4random() % 2) makes it be 0 or 1
(arc4random() % 2) * 2 makes it be 0 or 2
(arc4random() % 2) * 2 - 1 gives you -1 or 1

Related

Is there a shorthand notation for this operation?

Is there no shorthand notation like /= for this operation in C?
int variable = 5;
variable = round(variable / (float)2);
I can't think of any.
So it really depends what you're doing. Most of the time you shouldn't be actually concerned about shortcuts but readability and correctness. In this case your code is quite readable but it is not very correct, because it code divides by a float so the result has only23-24 bits of precision, less than in an int; even if you use a double 2.0, you get that 53-54 bits of precision which is less than long long int.
The codes below are likely not only faster but also work correctly in more cases.
If you want to work with unsigned numbers (or signed with non-negative values), then you can do this:
unsigned int variable = 5;
variable = (variable + 1) >> 1;
i.e. add 1 and bitshift right.
If you need to support signed and are using C99+ or C89 with properly-defined division (truncating towards zero), you can do
variable = (variable + (variable > 0 ? 1: -1)) / 2;
These work because integer division always return an integer:
#include <stdio.h>
int main(void) {
for (int i = -5; i <= 5; i ++) {
int variable = i;
variable = (variable + (variable > 0 ? 1: -1)) / 2;
printf("%3d\t%4.1f\t%3d\n", i, i/2.0, variable);
}
}
will print out:
-5 -2.5 -3
-4 -2.0 -2
-3 -1.5 -2
-2 -1.0 -1
-1 -0.5 -1
0 0.0 0
1 0.5 1
2 1.0 1
3 1.5 2
4 2.0 2
5 2.5 3

How does this recursive function return the correct answer?

I wanted to know how this function returns 4 which is the correct answer, when it resets the res variable every time the function calls itself.
num = 2367319
int func(int num)
{
int res = 0;
if (num > 0)
res = (num % 10 % 3 == 0 ? 1 : 0) + func(num / 10);
return res;
}
res isn't "reset". Rather a new local variable named res is created for each recursive call.
I suggest you add some printf() statements in order to see how this function works.
res equals the number of digits divisible with 3. It will always get a proper value, as long as num is still greater than 0.
For starters the declaration and the implementation of the function is bad.
The function parameter has the type int. So the user can supply a negative number and will await how many digits of the number are divisible by 3. However the function returns 0. A question arises: and what to do with negative numbers? To write one more function?
The second problem is that the function is unable to process integer numbers of types long int and long long int. Again do we need to write separate functions for these signed integer types?
The function uses an redundant variable res.
It can be declared and implemented the following way as it is shown in the demonstrative program below..
#include <stdio.h>
unsigned int func( long long int n )
{
const long long int Base = 10;
return n == 0 ? 0 : ( n % Base % 3 == 0 ) + func( n / Base );
}
int main(void)
{
printf( "%d : %u\n", 2367319, func( 2367319 ) );
printf( "%d : %u\n", -2367319, func( -2367319 ) );
return 0;
}
The program output is
2367319 : 4
-2367319 : 4
How does the function works?
If the n is equal to 0 then the function returns 0.
return n == 0 ? 0 : ( n % Base % 3 == 0 ) + func( n / Base );
^^^^^^ ^^
Otherwise if the last digit n % Base (the remainder of division by 10) of the number is divisible by 3 then this expression
return n == 0 ? 0 : ( n % Base % 3 == 0 ) + func( n / Base );
^^^^^^^^^^^^^^^^^^
yields 1 (true). Otherwise it yields 0. So the function counts the number of digits divisible by 3 in such a way recutsively.
For example let's consider the number 2367319.
The expression 2367319 % 10 yields the digit 9. 9 % 3 (2367319 % 10 % 3) is equal to 0. So the expression
2367319 % 10 % 3 == 0
yields 1.
Now the function calls itself with the number 2367319 / 10 that is with the number 236731. And the operation with the last digit of this new number is repeated. In this case the expression
236731 % 10 % 3 == 0
evaluates to 0 (false).
And so on. All results of the function calls are accumulated and returned.
In fact you will have
(2367319 % 10 % 3 == 0) + (236731 % 10 % 3 == 0) + (23673 % 10 % 3 == 0) +...+ 0
1 + 0 + 1 +...+ 0
In simple words, when function is called all it's local variables are created on stack(i.e stack pointer incremented by amount of local variables used). Upon function exit stack pointer is decremented by same amount.
Consider below example, function foo() with some bytes of local variables calling a bar() with some other bytes of local variable. (For simplistic purpose I have excluded the function return address from stack)
/*stack growth in this direction ---->*/
foo()-------+
|
/*foo code execution */
|
bar()----------+
|
/* bar() Code execution */
|
+------------+
|
|------------+
As functions is called stack is expanded and shrinks upon function exit.
In case of recursive function bar() happens to be foo() again and again. But new stack location is allocated for every function call.
And hence in your case res is being set to zero at different stack location even though it appears to be same variable name.

Should I use "rand % N" or "rand() / (RAND_MAX / N + 1)"?

I was reading the C FAQ and found out in a question that it recommends me to use rand() / (RAND_MAX / N + 1) instead of the more popular way which is rand() % N.
The reasoning for that is that when N is a low number rand() % N will only use a few bits from rand().
I tested the different approaches with N being 2 on both Windows and Linux but could not notice a difference.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 2
int main(void)
{
srand(0);
printf("rand() %% N:\n");
for (int i = 0; i < 40; ++i) {
printf("%d ", rand() % N);
}
putchar('\n');
srand(0);
printf("rand() / (RAND_MAX / N + 1):\n");
for (int i = 0; i < 40; ++i) {
printf("%d ", rand() / (RAND_MAX / N + 1));
}
putchar('\n');
return 0;
}
The output is this (on my gnu/linux machine):
rand() % N:
1 0 1 1 1 1 0 0 1 1 0 1 0 1 1 0 0 0 0 0 1 0 1 1 0 0 0 1 1 1 1 0 0 0 1 1 1 0 1 0
rand() / (RAND_MAX / N + 1):
1 0 1 1 1 0 0 1 0 1 0 1 0 1 1 1 1 1 0 1 0 0 0 1 0 0 0 0 1 0 1 1 1 0 1 1 0 1 0 1
Both alternatives seem perfectly random to me. It even seems like the second approach is worse than rand % N.
Should I use rand() % N or rand() / (RAND_MAX / N + 1)?
If N is a power of two, using the remainder technique is usually safe (RAND_MAX is usually a power of two minus 1, so the entire range has a power of two length). More generally, N has to divide the range of rand() in order to avoid the bias.
Otherwise, you run into this problem, regardless of the quality of rand(). In short, the problem is that you're chopping that range into a number of "parts" each of length N, if N does not divide the range then the last part will not be complete. The numbers that got "cut off" from that part are therefore less likely to occur, since they have one fewer "part" they can be generated from.
Unfortunately rand() / (RAND_MAX / N + 1) is also broken (in almost the same way), so the real answer is: don't use either of them.
The problem as outlined above is really fundamental, there is no way to evenly distribute X different values over Y results unless Y divides X. You can fix it by rejecting a part of the random samples, to make Y divide the new X.
There is another problem with rand() % n which is that it introduces a modulo bias.
For simplicity's sake let's pretend RAND_MAX is 7 and n is 6. You want the numbers 0, 1, 2, 3, 4, 5 to appear in the random stream with equal probability. However, 0 and 1 will appear 1/4 of the time and the other numbers only 1/8th of the time because 6 and 7 have remainders 0 and 1 respectively. You should use the other method, but carefully because truncation of fractions might introduce a similar issue.
If you have arc4random(), you can use arc4random_uniform() to achieve an unbiased distribution without having to be careful.
On avr-gcc:
I was using rand() & 0xFF to get random number from 0 to 255 and the results were not good. Turned out, that using lower bits is not very reliable method, often the same values. Could be similar with modulo.
rand() / (RAND_MAX / N + 1) worked much better for me

Issue with % operator in C

I am having an issue with the % operator in C. I know that the % operator gives the remainder of a division. However when faced with a question like 1 % 2 or 3 % 2, I get confused. After googling this, I found different solutions.
Some say that as 1 / 2 is 0.5, we round it down to 0. So 1 % 2 is 0.
Others say that as 1 / 2 is 0.5, we instead round it up, like we would in maths, to 1. So 1 % 2 is 1.
And therefore, I am now confused. My question is: What is 1 % 2?
Thank you in advance :):)
% is the remainder operator:
The % operator computes the remainder after dividing its first operand
by its second.
It's what left from the division. For example:
5 % 3 is 2.
5 % 4 is 1.
5 % 2 is 1. (Because 2 can fit 2 times in 5, 1 will be left)
When you do 1 % 2 the result is 1 because 1/2 is 0, and the remainder is.. 1.
Simply put, both are wrong methods. As you said % finds the remainder of division.
Therefore 1/2 is equal to 0 remainder 1.
And the answer is thus 1.
Also, to experiment yourself, you could have used this program:
#include <stdio.h>
main()
{
int remainder;
remainder = 1 % 2;
printf("1 %% 2 is %d", remainder);
return(0);
}
Hope this helps :)
The easy way to think of M % D (if both M and D are positive) is:
While ( M >= D){
M = M-D;
}
return M;
There is no rounding, the decimal part is simply truncated.
So, 1 / 2 is 0 and 1 % 2 is 1.
Here you need the mathematical definition on remainder.
Given two integer numbers m, d, we say that r is the remainder of the division of m and d if r satisfies two conditions:
There exists another integer k such that m == k * d + r , and
0 <= r < d.
In C we have m % d == r and m / d == k, just by following the definition above.
As you can see, there is no trucation at all (I mean: the "truncation" is consequence of the definition).
From the definition, it can be obtainded that 3 % 2 == 1 and 3 / 2 == 1.
Other examples:
4 / 3 == 1 and 5 / 3 == 1, in despite of 5.0/3.0 == 1.6666 (which
would round to 2.0).
4 % 3 == 1 and 5 % 3 == 2.
You can trust also in the formula r = m - k * d, which in C is written as:
m % d == m - (m / d) * d
However, in the standard C, the integer division follows the rule: round to 0.
Thus, with negative operands C offer different results that the mathematical ones.
We would have:
(-4) / 3 == -1, (-4) % 3 == -1 (in C), but in plain maths: (-4) / 3 = -2, (-4) % 3 = 2.
In plain maths, the remainder is always nonnegative, and less than the abs(d).
In standard C, the remainder always has the sign of the first operator.
Remark: This description (in the negative case) is for standard C99/C11 only. You must be carefull with your compiler version, and to do some tests.

How do I get a specific range of numbers from rand()?

srand(time(null));
printf("%d", rand());
Gives a high-range random number (0-32000ish), but I only need about 0-63 or 0-127, though I'm not sure how to go about it. Any help?
rand() % (max_number + 1 - minimum_number) + minimum_number
So, for 0-65:
rand() % (65 + 1 - 0) + 0
(obviously you can leave the 0 off, but it's there for completeness).
Note that this will bias the randomness slightly, but probably not anything to be concerned about if you're not doing something particularly sensitive.
You can use this:
int random(int min, int max){
return min + rand() / (RAND_MAX / (max - min + 1) + 1);
}
From the:
comp.lang.c FAQ list · Question 13.16
Q: How can I get random integers in a certain range?
A: The obvious way,
rand() % N /* POOR */
(which tries to return numbers from 0 to N-1) is poor, because the
low-order bits of many random number generators are distressingly
non-random. (See question 13.18.) A better method is something like
(int)((double)rand() / ((double)RAND_MAX + 1) * N)
If you'd rather not use floating point, another method is
rand() / (RAND_MAX / N + 1)
If you just need to do something with probability 1/N, you could use
if(rand() < (RAND_MAX+1u) / N)
All these methods obviously require knowing RAND_MAX (which ANSI #defines in <stdlib.h>), and assume that N is much less than RAND_MAX. When N is close to RAND_MAX, and if the range of the random number
generator is not a multiple of N (i.e. if (RAND_MAX+1) % N != 0), all
of these methods break down: some outputs occur more often than
others. (Using floating point does not help; the problem is that rand
returns RAND_MAX+1 distinct values, which cannot always be evenly
divvied up into N buckets.) If this is a problem, about the only thing
you can do is to call rand multiple times, discarding certain values:
unsigned int x = (RAND_MAX + 1u) / N;
unsigned int y = x * N;
unsigned int r;
do {
r = rand();
} while(r >= y);
return r / x;
For any of these techniques, it's straightforward to shift the range,
if necessary; numbers in the range [M, N] could be generated with
something like
M + rand() / (RAND_MAX / (N - M + 1) + 1)
(Note, by the way, that RAND_MAX is a constant telling you what the
fixed range of the C library rand function is. You cannot set RAND_MAX
to some other value, and there is no way of requesting that rand
return numbers in some other range.)
If you're starting with a random number generator which returns
floating-point values between 0 and 1 (such as the last version of
PMrand alluded to in question 13.15, or drand48 in question
13.21), all you have to do to get integers from 0 to N-1 is
multiply the output of that generator by N:
(int)(drand48() * N)
Additional links
References: K&R2 Sec. 7.8.7 p. 168
PCS Sec. 11 p. 172
Quote from: http://c-faq.com/lib/randrange.html
check here
http://c-faq.com/lib/randrange.html
For any of these techniques, it's straightforward to shift the range, if necessary; numbers in the range [M, N] could be generated with something like
M + rand() / (RAND_MAX / (N - M + 1) + 1)
Taking the modulo of the result, as the other posters have asserted will give you something that's nearly random, but not perfectly so.
Consider this extreme example, suppose you wanted to simulate a coin toss, returning either 0 or 1. You might do this:
isHeads = ( rand() % 2 ) == 1;
Looks harmless enough, right? Suppose that RAND_MAX is only 3. It's much higher of course, but the point here is that there's a bias when you use a modulus that doesn't evenly divide RAND_MAX. If you want high quality random numbers, you're going to have a problem.
Consider my example. The possible outcomes are:
rand()
freq.
rand() % 2
0
1/3
0
1
1/3
1
2
1/3
0
Hence, "tails" will happen twice as often as "heads"!
Mr. Atwood discusses this matter in this Coding Horror Article
The naive way to do it is:
int myRand = rand() % 66; // for 0-65
This will likely be a very slightly non-uniform distribution (depending on your maximum value), but it's pretty close.
To explain why it's not quite uniform, consider this very simplified example:
Suppose RAND_MAX is 4 and you want a number from 0-2. The possible values you can get are shown in this table:
rand() | rand() % 3
---------+------------
0 | 0
1 | 1
2 | 2
3 | 0
See the problem? If your maximum value is not an even divisor of RAND_MAX, you'll be more likely to choose small values. However, since RAND_MAX is generally 32767, the bias is likely to be small enough to get away with for most purposes.
There are various ways to get around this problem; see here for an explanation of how Java's Random handles it.
rand() will return numbers between 0 and RAND_MAX, which is at least 32767.
If you want to get a number within a range, you can just use modulo.
int value = rand() % 66; // 0-65
For more accuracy, check out this article. It discusses why modulo is not necessarily good (bad distributions, particularly on the high end), and provides various options.
As others have noted, simply using a modulus will skew the probabilities for individual numbers so that smaller numbers are preferred.
A very ingenious and good solution to that problem is used in Java's java.util.Random class:
public int nextInt(int n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while (bits - val + (n-1) < 0);
return val;
}
It took me a while to understand why it works and I leave that as an exercise for the reader but it's a pretty concise solution which will ensure that numbers have equal probabilities.
The important part in that piece of code is the condition for the while loop, which rejects numbers that fall in the range of numbers which otherwise would result in an uneven distribution.
double scale = 1.0 / ((double) RAND_MAX + 1.0);
int min, max;
...
rval = (int)(rand() * scale * (max - min + 1) + min);
Updated to not use a #define
double RAND(double min, double max)
{
return (double)rand()/(double)RAND_MAX * (max - min) + min;
}
If you don't overly care about the 'randomness' of the low-order bits, just rand() % HI_VAL.
Also:
(double)rand() / (double)RAND_MAX; // lazy way to get [0.0, 1.0)
This answer does not focus on the randomness but on the arithmetic order.
To get a number within a range, usually we can do it like this:
// the range is between [aMin, aMax]
double f = (double)rand() / RAND_MAX;
double result = aMin + f * (aMax - aMin);
However, there is a possibility that (aMax - aMin) overflows. E.g. aMax = 1, aMin = -DBL_MAX. A safer way is to write like this:
// the range is between [aMin, aMax]
double f = (double)rand() / RAND_MAX;
double result = aMin - f * aMin + f * aMax;
Based on this concept, something like this may cause a problem.
rand() % (max_number + 1 - minimum_number) + minimum_number
// 1. max_number + 1 might overflow
// 2. max_number + 1 - min_number might overflow
if you care about the quality of your random numbers don't use rand()
use some other prng like http://en.wikipedia.org/wiki/Mersenne_twister or one of the other high quality prng's out there
then just go with the modulus.
Just to add some extra detail to the existing answers.
The mod % operation will always perform a complete division and therefore yield a remainder less than the divisor.
x % y = x - (y * floor((x/y)))
An example of a random range finding function with comments:
uint32_t rand_range(uint32_t n, uint32_t m) {
// size of range, inclusive
const uint32_t length_of_range = m - n + 1;
// add n so that we don't return a number below our range
return (uint32_t)(rand() % length_of_range + n);
}
Another interesting property as per the above:
x % y = x, if x < y
const uint32_t value = rand_range(1, RAND_MAX); // results in rand() % RAND_MAX + 1
// TRUE for all x = RAND_MAX, where x is the result of rand()
assert(value == RAND_MAX);
result of rand()
2 cents (ok 4 cents):
n = rand()
x = result
l = limit
n/RAND_MAX = x/l
Refactor:
(l/1)*(n/RAND_MAX) = (x/l)*(l/1)
Gives:
x = l*n/RAND_MAX
int randn(int limit)
{
return limit*rand()/RAND_MAX;
}
int i;
for (i = 0; i < 100; i++) {
printf("%d ", randn(10));
if (!(i % 16)) printf("\n");
}
> test
0
5 1 8 5 4 3 8 8 7 1 8 7 5 3 0 0
3 1 1 9 4 1 0 0 3 5 5 6 6 1 6 4
3 0 6 7 8 5 3 8 7 9 9 5 1 4 2 8
2 7 8 9 9 6 3 2 2 8 0 3 0 6 0 0
9 2 2 5 6 8 7 4 2 7 4 4 9 7 1 5
3 7 6 5 3 1 2 4 8 5 9 7 3 1 6 4
0 6 5
Just using rand() will give you same random numbers when running program multiple times. i.e. when you run your program first time it would produce random number x,y and z. If you run the program again then it will produce same x,y and z numbers as observed by me.
The solution I found to keep it unique every time is using srand()
Here is the additional code,
#include<stdlib.h>
#include<time.h>
time_t t;
srand((unsigned) time(&t));
int rand_number = rand() % (65 + 1 - 0) + 0 //i.e Random numbers in range 0-65.
To set range you can use formula : rand() % (max_number + 1 - minimum_number) + minimum_number
Hope it helps!
You can change it by adding a % in front of the rand function in order to change to code
For example:
rand() % 50
will give you a random number in a range of 50. For you, replace 50 with 63 or 127
I think the following does it semi right. It's been awhile since I've touched C. The idea is to use division since modulus doesn't always give random results. I added 1 to RAND_MAX since there are that many possible values coming from rand including 0. And since the range is also 0 inclusive, I added 1 there too. I think the math is arranged correctly avoid integer math problems.
#define MK_DIVISOR(max) ((int)((unsigned int)RAND_MAX+1/(max+1)))
num = rand()/MK_DIVISOR(65);
Simpler alternative to #Joey's answer. If you decide to go with the % method, you need to do a reroll to get the correct distribution. However, you can skip rerolls most of the time because you only need to avoid numbers that fall in the last bucket:
int rand_less_than(int max) {
int last_bucket_min = RAND_MAX - RAND_MAX % max;
int value;
do {
value = rand();
} while (last_bucket_min <= value);
return value % max;
}
See #JarosrawPawlak's article for explanation with diagrams: Random number generator using modulo
In case of RAND_MAX < max, you need to expand the generator: Expand a random range from 1–5 to 1–7
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // this line is necessary
int main() {
srand(time(NULL)); // this line is necessary
int random_number = rand() % 65; // [0-64]
return 0;
}
Foy any range between min_num and max_num:
int random_number = rand() % (max_num + 1 - min_num) + min_num;

Resources