Which one is the correct way of using "arc4rand()" - objective-c

I am new to objective C and trying to understand arc4random().
There are so many conflicting explanations on the web. Please clear my confusion, which of the following is correct:
// 1.
arc4random() % (toNumber - fromNumber) + fromNumber;
OR
//2.
arc4random() % ((toNumber - fromNumber) + 1) + fromNumber;
//toNumber-fromNumbers are any range of numbers like random # between 7-90.

This code will get you a random number between 7 and 90.
NSUInteger random = 7 + arc4random_uniform(90 - 7);
Use arc4random_uniform to avoid modulo bias.

Adam's answer is correct. However, just to clarify the difference between the two, the second one raises the possible range by one to make the range inclusive. The important thing to remember is that modulo is remainder division, so while there are toNumber possible outcomes, one of them is zero (if the result of arc4random() is a multiple of toNumber) and toNumber itself can not be the remainder.
// 1.
arc4random() % (10 - 5) + 5;
This results in a range of 0 + 5 to 4 + 5, which is 5 to 9.
//2.
arc4random() % ((10 - 5) + 1) + 5;
This results in a range of 0 + 5 to (4 + 1) + 5, which is 5 to 10.
Neither is correct or incorrect if you wish to use modulo. One is exclusive of the upper range while the other is inclusive of the upper range. However, if you think about how remainder division works and think of the pool of numbers returned by any PRNG in terms of cycles the length of your total range, then you'll realize that if the range does not divide evenly into the maximum range of the pool you'll get biased results. For instance, if arc4random() returned a result from 1 to 5 (it doesn't, obviously) and you wanted a number from 0 to 2, and you used arc4random() % 3, these are the possible results.
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
4 % 3 = 1
5 % 3 = 2
Note that there are two ones and two twos, but only one zero. This is because our range of 3 does not evenly divide into the PRNG's range of 5. The result is that (humorously enough) PRNG range % desired range numbers at the end of the cycle need to be culled because they are "biased"–the numbers themselves aren't really biased, but it's easier to cull from the end. Failing to do this results in the lower numbers of the range becoming more likely to appear.
We can cull the numbers by calculating the upper range of the numbers we can generate, modulo it with the desired range and then pull those numbers off of the end. By "pull those numbers off of the end" I really mean "loop infinitely until we get a number that isn't one of the end numbers".
Some would say that's bad practice; you could theoretically loop forever. In practice, however, the expected number of retries is always less than one since the modulo bias is never more than half the pool (usually much less than that) of the PRNG's numbers. I once wrote a wrapper for rand using this technique.
You can see an example of this in the source for OpenBSD, where arc4random_uniform calls arc4random in a loop until a number is determined to be clean.

Related

VB.NET doesn't round numbers correctly?

I'm testing the speed of some functions so I made a test to run the functions over and over again and I stored the results in an array. I needed them to be sorted by the size of the array I randomly generated. I generate 100 elements. Merge sort to the rescue! I used this link to get me started.
The section of code I'm focusing on:
private void mergesort(int low, int high) {
// check if low is smaller then high, if not then the array is sorted
if (low < high) {
// Get the index of the element which is in the middle
int middle = low + (high - low) / 2;
// Sort the left side of the array
mergesort(low, middle);
// Sort the right side of the array
mergesort(middle + 1, high);
// Combine them both
merge(low, middle, high);
}
}
which translated to VB.NET is
private sub mergesort(low as integer, high as integer)
' check if low is smaller then high, if not then the array is sorted
if (low < high)
' Get the index of the element which is in the middle
dim middle as integer = low + (high - low) / 2
' Sort the left side of the array
mergesort(low, middle)
' Sort the right side of the array
mergesort(middle + 1, high)
' Combine them both
merge(low, middle, high)
end if
end sub
Of more importance the LOC that only matters to this question is
dim middle as integer = low + (high - low) / 2
In case you wanna see how merge sort is gonna run this baby
high low high low
100 0 10 0
50 0 6 4
25 0 5 4
12 0 12 7
6 0 10 7
3 0 8 7
2 0 :stackoverflow error:
The error comes from the fact 7 + (8 - 7) / 2 = 8. You'll see 7 and 8 get passed in to mergesort(low, middle) and then we infinite loop. Now earlier in the sort you see a comparison like this again. At 5 and 4. 4 + (5 - 4) / 2 = 4. So essentially for 5 and 4 it becomes 4 + (1) / 2 = 4.5 = 4. For 8 and 7 though it's 7 + (1) / 2 = 7.5 = 8. Remember the numbers are typecasted to an int.
Maybe I'm just using a bad implementation of it or my typecasting is wrong, but my question is: Shouldn't this be a red flag signaling something isn't right with the rounding that's occuring?
Without understanding the whole algorithm, note that VB.NET / is different than C# /. The latter has integer division by default, if you want to truncate decimal places also in VB.NET you have to use \.
Read: \ Operator
So i think that this is what you want:
Dim middle as Int32 = low + (high - low) \ 2
You are correct in your diagnosis: there's something inconsistent with the rounding that's occurring, but this is entirely expected if you know where to look.
From the VB.NET documentation on the / operator:
Divides two numbers and returns a floating-point result.
This documentation explicitly states that , if x and y are integral types, x / y returns a Double. So, 5 / 2 in VB.NET would be expected to be 2.5.
From the C# documentation on the / operator:
All numeric types have predefined division operators.
And further down the page:
When you divide two integers, the result is always an integer.
In the case of C#, if x and y are integers, x / y returns an integer (rounded down). 5 / 2 in C# is expected to return 2.

What is the difference between MOD and REMAINDER in oracle?

Although both the functions perform the same operation, even they produce same o/p, what is basic difference between these two? Is there any performance related difference, if yes, then which one is better?
Thanks
The documentation is pretty clear on the difference:
NOTE
The REMAINDER function uses the round function in its formula, whereas
the MOD function uses the floor function in its formula.
In other words, when the arguments are positive integers, the mod function returns a positive number between 0 and the second argument. The remainder function returns a number whose absolute value is less than the second argument divided by 2.
The differences can be more striking for negative numbers. One example of a difference is:
REMAINDER(-15, 4)
MOD(-15, 4)
The first gives -3 and the second 1.
EDIT:
What is happening here? How many times does 4 go into -15. One method is "-4" times with a remained of 1. That is: -15 = 4*(-4) + 1. The other is "-3" times: -15 = 4*(-3) - 3.
The difference what is -15/4 expressed as an integer. Using floor, you get -4. Using round, you get -3.
The difference between MOD and REMAINDER function can be understood in the example below:
MOD(13,5): returns 3 whereas, REMAINDER (13,5) returns -2
A simple way to understand the difference is that MOD uses the floor function therefore it counts the occurrence of the second number within the first and returns what is left to complete the first number i.e. 2(5) gives 10 adding 3 gives 13 therefore MOD(13,5)=3
However, the REMAINDER uses a Round function it therefore gets the total number of the second number that could make up the first and then subtract the what makes it excess. i.e. 3(5) = 15 and subtracting 2 gives 13,therefore REMAINDER(13,5)= -2
REMAINDER (-15, 4): 4(-4) gives -16 and adding +1 gives -15 hence REMAINDER (-15,4)=+1
MOD (-15, 4): 3(-4) gives -12, adding -3 gives us -15 hence MOD(15,4)=-3
REMAINDER(-15, 4)--uses round without taking the sign of the number into
consideration.
hence -15/4= -3.75==> round(-3.75)= -4.--(ignore sign during round)
-4*4= -16
-15-(-16)=>1
There fore: REMAINDER(-15, 4)=1
MOD(-15, 4)----uses Floor without taking the sign of the number into
consideration.
-15/4= -3.75==> floor(-3.75)= -3.--(ignore sign in floor)
-3*4=-12
-15-(-12)=>-3
There fore: MOD(-15, 4)= -3
Mod(m,n) is so simple to understand.
Finding Value Mod() output value will always be the manually calculated remainder value when we divide m by n.
Finding Sign The sign of the output remains the same as the first parameter.
eg :
eg 1 : mod (11,3) is the remainder of 11/3 which is 2 and the same sign of 1st parameter. So output is 2
eg 2 : mod (-11,3) is the remainder of 11/3 which is 2 and the same sign of the 1st parameter. So the output is -2
Remainder(m,n) is a bit different
Finding Value You take two multiples of n, such that when multiplied gives the closest lower value and the closest upper value compared to the first parameter(m). The minimum difference between these values will be the output value
Finding Sign The sign of the output value will always be positive if the closest value is less than the first parameter and the if the closest value is greater than the 1st parameter then it will be negative.
eg :
eg 1 : remainder(10,3) The closest multiple values of 3 which are lesser and greater than 10 are 9(3x3) and 12(3x4). And the closest to 10 among 9 & 12 is 9. So the output will be the gap between 9 and 10 which is 1. The closest number is less than the 1st parameter. So the output is 1.
eg 2 : remainder(11,3) The closest multiple values of 11 which are lesser and greater than 11 are 9(3x3) and 12(3x4). And the closest to 12 among 9 & 12 is 12. So the output will be the gap between 12 and 11 which is 1. The closest number is greater than the 1st parameter. So the output is -1.
The question has long had an answer, but I thought some context would be helpful.
https://en.wikipedia.org/wiki/Modulo_operation discusses the “modulo” operation, and the fact that it is based on the remainder after integer division. The problem is that the concept of “remainder” is not clearly defined where there are negative numbers.
Where negative numbers are involved, the difference between modulus and remainder is significant. Mathematically, the modulus operation maps an integer on to a range. This range begins at 0 and is cyclic. For example integer mod 3 is mapped on to the range:
0, 1, 2, 0, 1, 2, …
If the given integer is negative, the cycle is simply extended backwards. If, however, the modulus itself is negative, then the whole range is negative:
0, -2, -1, 0, -2, -1, …
https://rob.conery.io/2018/08/21/mod-and-remainder-are-not-the-same/ illustrates this as a clock with negative numbers.
The practical upshot of this is that the sign of the second number is the same as the sign of the result.
With a remainder, however, you attempt to divide the second number into the first number until you can’t go any more. The remaining difference is called the remainder. If the first number is negative, then, if you stop short, the remainder will be negative.
The practical upshot of which is that the sign of the first number is the sign of the result.
Most coding languages, including most variations of SQL, use a remainder calculation, but very often call it the modulus. And most languages use the notation a % b meaning a mod b.
Oracle, of course, has two functions, which should have been helpful. However, the first function, mod(), actually gives what everybody else calls the remainder. The second, remainder() gives a result which nobody else gives, due to the fact that it is focused on the nearest division. As per the documentation, the mod() functions uses the floor() function, while remainder() uses round().
If you want to compare the results, you can try:
SELECT
remainder(19,5) AS "Remainder ++",
remainder(-19,5) AS "Remainder -+",
remainder(19,-5) AS "Remainder +-",
remainder(-19,-5) AS "Remainder --",
mod(19,5) AS "Mod ++",
mod(-19,5) AS "Mod -+",
mod(19,-5) AS "Mod +-",
mod(-19,-5) AS "Mod --",
mod(mod(19,5) + 5,5) AS "Modulo ++",
mod(mod(-19,5) + 5,5) AS "Modulo ++",
mod(mod(19,-5) + -5,-5) AS "Modulo ++",
mod(mod(-19,-5) + -5,-5) AS "Modulo ++"
FROM DUAL
;
The modulo calculation gives the true modulus, according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder
In all, you probably want the remainder as the most natural interpretation, and so you will use mod() to get this result.

How to exclude numbers in arc4random?

I am using arc4random to generate a random number. I would like to generate a number between 1-9. How can I exclude 0?
int r = arc4random() % (9);
NSLog(#"Random Number: %d",r);
int r = (arc4random() % 8) + 1
You can use arc4random_uniform(), as in
arc4random_uniform(9) + 1
Generally, to generate a number between lo and hi (inclusive), you use:
arc4random_uniform(hi - lo + 1) + lo
If you don't want to use arc4random_uniform() and want to stick with arc4random(), noting that the resulting value from using modulus formula is not uniformly distributed, use
(arc4random() % (hi - lo + 1)) + lo
int r = arc4random() % 8 + 1;
See other answers (e.g., one from me) for why you probably don't want to use % for this task, and what you should use instead.
You could simply try repeatedly until you get a number in the range you want, throwing out numbers you don't want. This has the fancy name "acceptance-rejection method" in math. It's simple, and it works.
In case you're worried that this could take a long time, in theory it could. But this approach is used all the time in statistical applications. The probability of going through a while-loop N times decreases rapidly as N increases, so the average number of times through the loop is small.

Recognizing when to use the modulus operator

I know the modulus (%) operator calculates the remainder of a division. How can I identify a situation where I would need to use the modulus operator?
I know I can use the modulus operator to see whether a number is even or odd and prime or composite, but that's about it. I don't often think in terms of remainders. I'm sure the modulus operator is useful, and I would like to learn to take advantage of it.
I just have problems identifying where the modulus operator is applicable. In various programming situations, it is difficult for me to see a problem and realize "Hey! The remainder of division would work here!".
Imagine that you have an elapsed time in seconds and you want to convert this to hours, minutes, and seconds:
h = s / 3600;
m = (s / 60) % 60;
s = s % 60;
0 % 3 = 0;
1 % 3 = 1;
2 % 3 = 2;
3 % 3 = 0;
Did you see what it did? At the last step it went back to zero. This could be used in situations like:
To check if N is divisible by M (for example, odd or even)
or
N is a multiple of M.
To put a cap of a particular value. In this case 3.
To get the last M digits of a number -> N % (10^M).
I use it for progress bars and the like that mark progress through a big loop. The progress is only reported every nth time through the loop, or when count%n == 0.
I've used it when restricting a number to a certain multiple:
temp = x - (x % 10); //Restrict x to being a multiple of 10
Wrapping values (like a clock).
Provide finite fields to symmetric key algorithms.
Bitwise operations.
And so on.
One use case I saw recently was when you need to reverse a number. So that 123456 becomes 654321 for example.
int number = 123456;
int reversed = 0;
while ( number > 0 ) {
# The modulus here retrieves the last digit in the specified number
# In the first iteration of this loop it's going to be 6, then 5, ...
# We are multiplying reversed by 10 first, to move the number one decimal place to the left.
# For example, if we are at the second iteration of this loop,
# reversed gonna be 6, so 6 * 10 + 12345 % 10 => 60 + 5
reversed = reversed * 10 + number % 10;
number = number / 10;
}
Example. You have message of X bytes, but in your protocol maximum size is Y and Y < X. Try to write small app that splits message into packets and you will run into mod :)
There are many instances where it is useful.
If you need to restrict a number to be within a certain range you can use mod. For example, to generate a random number between 0 and 99 you might say:
num = MyRandFunction() % 100;
Any time you have division and want to express the remainder other than in decimal, the mod operator is appropriate. Things that come to mind are generally when you want to do something human-readable with the remainder. Listing how many items you could put into buckets and saying "5 left over" is good.
Also, if you're ever in a situation where you may be accruing rounding errors, modulo division is good. If you're dividing by 3 quite often, for example, you don't want to be passing .33333 around as the remainder. Passing the remainder and divisor (i.e. the fraction) is appropriate.
As #jweyrich says, wrapping values. I've found mod very handy when I have a finite list and I want to iterate over it in a loop - like a fixed list of colors for some UI elements, like chart series, where I want all the series to be different, to the extent possible, but when I've run out of colors, just to start over at the beginning. This can also be used with, say, patterns, so that the second time red comes around, it's dashed; the third time, dotted, etc. - but mod is just used to get red, green, blue, red, green, blue, forever.
Calculation of prime numbers
The modulo can be useful to convert and split total minutes to "hours and minutes":
hours = minutes / 60
minutes_left = minutes % 60
In the hours bit we need to strip the decimal portion and that will depend on the language you are using.
We can then rearrange the output accordingly.
Converting linear data structure to matrix structure:
where a is index of linear data, and b is number of items per row:
row = a/b
column = a mod b
Note above is simplified logic: a must be offset -1 before dividing & the result must be normalized +1.
Example: (3 rows of 4)
1 2 3 4
5 6 7 8
9 10 11 12
(7 - 1)/4 + 1 = 2
7 is in row 2
(7 - 1) mod 4 + 1 = 3
7 is in column 3
Another common use of modulus: hashing a number by place. Suppose you wanted to store year & month in a six digit number 195810. month = 195810 mod 100 all digits 3rd from right are divisible by 100 so the remainder is the 2 rightmost digits in this case the month is 10. To extract the year 195810 / 100 yields 1958.
Modulus is also very useful if for some crazy reason you need to do integer division and get a decimal out, and you can't convert the integer into a number that supports decimal division, or if you need to return a fraction instead of a decimal.
I'll be using % as the modulus operator
For example
2/4 = 0
where doing this
2/4 = 0 and 2 % 4 = 2
So you can be really crazy and let's say that you want to allow the user to input a numerator and a divisor, and then show them the result as a whole number, and then a fractional number.
whole Number = numerator/divisor
fractionNumerator = numerator % divisor
fractionDenominator = divisor
Another case where modulus division is useful is if you are increasing or decreasing a number and you want to contain the number to a certain range of number, but when you get to the top or bottom you don't want to just stop. You want to loop up to the bottom or top of the list respectively.
Imagine a function where you are looping through an array.
Function increase Or Decrease(variable As Integer) As Void
n = (n + variable) % (listString.maxIndex + 1)
Print listString[n]
End Function
The reason that it is n = (n + variable) % (listString.maxIndex + 1) is to allow for the max index to be accounted.
Those are just a few of the things that I have had to use modulus for in my programming of not just desktop applications, but in robotics and simulation environments.
Computing the greatest common divisor
Determining if a number is a palindrome
Determining if a number consists of only ...
Determining how many ... a number consists of...
My favorite use is for iteration.
Say you have a counter you are incrementing and want to then grab from a known list a corresponding items, but you only have n items to choose from and you want to repeat a cycle.
var indexFromB = (counter-1)%n+1;
Results (counter=indexFromB) given n=3:
`1=1`
`2=2`
`3=3`
`4=1`
`5=2`
`6=3`
...
Best use of modulus operator I have seen so for is to check if the Array we have is a rotated version of original array.
A = [1,2,3,4,5,6]
B = [5,6,1,2,3,4]
Now how to check if B is rotated version of A ?
Step 1: If A's length is not same as B's length then for sure its not a rotated version.
Step 2: Check the index of first element of A in B. Here first element of A is 1. And its index in B is 2(assuming your programming language has zero based index).
lets store that index in variable "Key"
Step 3: Now how to check that if B is rotated version of A how ??
This is where modulus function rocks :
for (int i = 0; i< A.length; i++)
{
// here modulus function would check the proper order. Key here is 2 which we recieved from Step 2
int j = [Key+i]%A.length;
if (A[i] != B[j])
{
return false;
}
}
return true;
It's an easy way to tell if a number is even or odd. Just do # mod 2, if it is 0 it is even, 1 it is odd.
Often, in a loop, you want to do something every k'th iteration, where k is 0 < k < n, assuming 0 is the start index and n is the length of the loop.
So, you'd do something like:
int k = 5;
int n = 50;
for(int i = 0;i < n;++i)
{
if(i % k == 0) // true at 0, 5, 10, 15..
{
// do something
}
}
Or, you want to keep something whitin a certain bound. Remember, when you take an arbitrary number mod something, it must produce a value between 0 and that number - 1.

Weird Objective-C Mod Behavior for Negative Numbers

So I thought that negative numbers, when mod'ed should be put into positive space... I cant get this to happen in objective-c
I expect this:
-1 % 3 = 2
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
But get this
-1 % 3 = -1
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
Why is this and is there a workaround?
result = n % 3;
if( result < 0 ) result += 3;
Don't perform extra mod operations as suggested in the other answers. They are very expensive and unnecessary.
In C and Objective-C, the division and modulus operators perform truncation towards zero. a / b is floor(a / b) if a / b > 0, otherwise it is ceiling(a / b) if a / b < 0. It is always the case that a == (a / b) * b + (a % b), unless of course b is 0. As a consequence, positive % positive == positive, positive % negative == positive, negative % positive == negative, and negative % negative == negative (you can work out the logic for all 4 cases, although it's a little tricky).
If n has a limited range, then you can get the result you want simply by adding a known constant multiple of 3 that is greater that the absolute value of the minimum.
For example, if n is limited to -1000..2000, then you can use the expression:
result = (n+1002) % 3;
Make sure the maximum plus your constant will not overflow when summed.
We have a problem of language:
math-er-says: i take this number plus that number mod other-number
code-er-hears: I add two numbers and then devide the result by other-number
code-er-says: what about negative numbers?
math-er-says: WHAT? fields mod other-number don't have a concept of negative numbers?
code-er-says: field what? ...
the math person in this conversations is talking about doing math in a circular number line. If you subtract off the bottom you wrap around to the top.
the code person is talking about an operator that calculates remainder.
In this case you want the mathematician's mod operator and have the remainder function at your disposal. you can convert the remainder operator into the mathematician's mod operator by checking to see if you fell of the bottom each time you do subtraction.
If this will be the behavior, and you know that it will be, then for m % n = r, just use r = n + r. If you're unsure of what will happen here, use then r = r % n.
Edit: To sum up, use r = ( n + ( m % n ) ) % n
I would have expected a positive number, as well, but I found this, from ISO/IEC 14882:2003 : Programming languages -- C++, 5.6.4 (found in the Wikipedia article on the modulus operation):
The binary % operator yields the remainder from the division of the first expression by the second. .... If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined
JavaScript does this, too. I've been caught by it a couple times. Think of it as a reflection around zero rather than a continuation.
Why: because that is the way the mod operator is specified in the C-standard (Remember that Objective-C is an extension of C). It confuses most people I know (like me) because it is surprising and you have to remember it.
As to a workaround: I would use uncleo's.
UncleO's answer is probably more robust, but if you want to do it on a single line, and you're certain the negative value will not be more negative than a single iteration of the mod (for example if you're only ever subtracting at most the mod value at any time) you can simplify it to a single expression:
int result = (n + 3) % 3;
Since you're doing the mod anyway, adding 3 to the initial value has no effect unless n is negative (but not less than -3) in which case it causes result to be the expected positive modulus.
There are two choices for the remainder, and the sign depends on the language. ANSI C chooses the sign of the dividend. I would suspect this is why you see Objective-C doing so also. See the wikipedia entry as well.
Not only java script, almost all the languages shows the wrong answer'
what coneybeare said is correct, when we have mode'd we have to get remainder
Remainder is nothing but which remains after division and it should be a positive integer....
If you check the number line you can understand that
I also face the same issue in VB and and it made me to forcefully add extra check like
if the result is a negative we have to add the divisor to the result
Instead of a%b
Use: a-b*floor((float)a/(float)b)
You're expecting remainder and are using modulo. In math they are the same thing, in C they are different. GNU-C has Rem() and Mod(), objective-c only has mod() so you will have to use the code above to simulate rem function (which is the same as mod in the math world, but not in the programming world [for most languages at least])
Also note you could define an easy to use macro for this.
#define rem(a,b) ((int)(a-b*floor((float)a/(float)b)))
Then you could just use rem(-1,3) in your code and it should work fine.