Modulus operator nim - modulus

What is the modulus operator in Nim?
tile % 9 == 0 results in undeclared identifier: '%'
Googling or searching SO doesn't bring up an answer.

Others have suggested using %%, but don't do that. It is a remnant of a time when Nim used to have only signed integers. The operators ending with % like <% are used to handle these signed integers as unsigned ints. Since Nim has had unsigned integers for a while now, simply use the mod operator that is correctly overloaded for all relevant integral types: https://nim-lang.org/docs/system.html#mod,int,int

You can use the modulus operator with the mod keyword like this:
tile mod 9 == 0

Related

What's the point of Raku's 'mod' operator?

I previously incorrectly thought that the % operator returned the remainder and the mod operator returned the modulus (the remainder and modulus are the same when the operands are both positive or both negative but differ when one operand is positive and the other is negative. Compare Raket's remainder and modulo functions).
However, that's not correct at all – both % and mod return the modulus; neither return the remainder. In fact, it looks like mod will always return exactly the same value as % would have, if called with the same arguments. As far as I can tell, the only difference is that % can be called with non-integer arguments, whereas mod throws an exception if called with anything other than Int:D or int.
So, what's the point of mod? Is there some performance gain from using it (maybe by saving the optimizer some specialization work?) or is there some other difference I'm missing?
TL;DR My takeaway from a quick skim of sources is that % is (supposed to be) the rational or generic modulus op, whereas mod is a dedicated integer modulus op. For some inputs they yield the same result.
The rest of this answer just references the sources I looked at.
Doc
mod:
Integer modulo operator. Returns the remainder of an integer modulo operation.
%:
Modulo operator. Coerces to Numeric first.
Generally the following identity holds:
my ($x, $y) = 1,2;
$x % $y == $x - floor($x / $y) * $y
roast
Search of roast for modulus lists just S03-operators/arith.t. Leads to:
infix:<%> should return Rat when it can.
"TimToady thinks modmap (or whatever we decide to call it) would be a useful addition to the language". (Off topic but interesting.)
S03
infix:<%>, modulo
coerces ... then calculates the remainder ... defined as:
$x % $y == $x - floor($x / $y) * $y
If both operands are of integer or rational type, the operator returns the corresponding Rat value (except when the result does not fit into a Rat, as detailed in S02).
infix:<mod>, integer modulo
Dispatches to the infix:<mod> multi most appropriate to the operand types, returning a value of the same type. Not coercive, so fails on differing types.
This should preserve the identity:
$x mod $y == $x - ($x div $y) * $y
IRC
Search of #perl6 for mod integer.
Rakudo source code
infix:<%>
infix:<mod>
The 'bible' of IEEE P754 says this...
Floating point remainder. This is not like a normal modulo operation, it can be negative for two positive numbers. It returns the exact value of x–(round(x/y)·y).

How do I seed the rand() function in Objective-C?

Part of what I'm developing is a random company name generator. It draws from several arrays of name parts. I use the rand() function to draw the random name parts. However, the same "random" numbers are always generated in the same sequence every time I launch the app, so the same names always appear.
So I searched around SO, and in C there is an srand() function to "seed" the random function with something like the current time to make it more random - like srand(time(NULL)). Is there something like that for Objective-C that I can use for iOS development?
Why don't you use arc4random which doesn't require a seed? You use it like this:
int r = arc4random();
Here's an article comparing it to rand(). The arc4random() man page says this about it in comparison to rand():
The arc4random() function uses the key stream generator employed by the arc4 cipher, which uses 8*8 8
bit S-Boxes. The S-Boxes can be in about (21700) states. The arc4random() function returns pseudo-
random numbers in the range of 0 to (232)-1, and therefore has twice the range of rand(3) and
random(3).
If you want a random number within a range, you can use the arc4random_uniform() function. For example, to generate a random number between 0 and 10, you would do this:
int i = arc4random_uniform(11);
Here's some info from the man page:
arc4random_uniform(upper_bound) will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.
The functions rand() and srand() are part of the Standard C Library and like the rest of the C library fully available for you to us in iOS development with Objective-C. Note that these routines have been superseded by random() and srandom(), which have almost identically calling conventions to rand() and srand() but produce much better results with a larger period. There is also an srandomdev() routine which initializes the state of the random number generator using the random number device. These are also part of the Standard C Library and available for use on iOS in Objective-C.

How to set any single bit in a Short

If varShort in VB.NET is a Short and varBit is a value from 0 to 15, how can I set the bit in varShort identified by varBit without disturbing any of the other bits in varShort?
My problem, of course, is with the most significant bit, bit 15. Since varBit is determined at runtime, the solution must work with any bit number.
You can use the bitshift operators, << and >>, to turn on the bit you want (and put this value in varValue), and then bitwise Or varShort and varValue
There is information in this question about the bitshift operators in VB.NET
Setting the sixteenth bit of a Short will cause an overflow exception because Short is a signed type. Do you have any reason not to use the unsigned counterpart UShort?
Edit
If you really want to stick with Short, this function will set the sixteenth bit:
Function setNthBit(ByVal number As Short, ByVal bit As Short) As Short
Dim mask As UShort
mask = 2 ^ bit
If mask > Short.MaxValue Then
Return (Short.MinValue + number) Or mask
Else
Return number Or mask
End If
End Function

How can I do a bitwise-AND operation in VB.NET?

I want to perform a bitwise-AND operation in VB.NET, taking a Short (16-bit) variable and ANDing it with '0000000011111111' (thereby retaining only the least-significant byte / 8 least-significant bits).
How can I do it?
0000000011111111 represented as a VB hex literal is &HFF (or &H00FF if you want to be explicit), and the ordinary AND operator is actually a bitwise operator. So to mask off the top byte of a Short you'd write:
shortVal = shortVal AND &HFF
For more creative ways of getting a binary constant into VB, see: VB.NET Assigning a binary constant
Use the And operator, and write the literal in hexadecimal (easy conversion from binary):
theShort = theShort And &h00ff
If what you are actually trying to do is to divide the short into bytes, there is a built in method for that:
Dim bytes As Byte() = BitConverter.GetBytes(theShort)
Now you have an array with two bytes.
result = YourVar AND cshort('0000000011111111')

What are the practical uses of modulus (%) in programming? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Recognizing when to use the mod operator
What are the practical uses of modulus? I know what modulo division is. The first scenario which comes to my mind is to use it to find odd and even numbers, and clock arithmetic. But where else I could use it?
The most common use I've found is for "wrapping round" your array indices.
For example, if you just want to cycle through an array repeatedly, you could use:
int a[10];
for (int i = 0; true; i = (i + 1) % 10)
{
// ... use a[i] ...
}
The modulo ensures that i stays in the [0, 10) range.
I usually use them in tight loops, when I have to do something every X loops as opposed to on every iteration..
Example:
int i;
for (i = 1; i <= 1000000; i++)
{
do_something(i);
if (i % 1000 == 0)
printf("%d processed\n", i);
}
One use for the modulus operation is when making a hash table. It's used to convert the value out of the hash function into an index into the array. (If the hash table size is a power of two, the modulus could be done with a bit-mask, but it's still a modulus operation.)
To print a number as string, you need the modulus to find the value of a digit.
string number_to_string(uint number) {
string result = "";
while (number != 0) {
result = cast(char)((number % 10) + '0') ~ result;
// ^^^^^^^^^^^
number /= 10;
}
return result;
}
For the control number of international bank account numbers, the mod97 technique.
Also in large batches to do something after n iterations. Here is an example for NHibernate:
ISession session = sessionFactory.openSession();
ITransaction tx = session.BeginTransaction();
for ( int i=0; i<100000; i++ ) {
Customer customer = new Customer(.....);
session.Save(customer);
if ( i % 20 == 0 ) { //20, same as the ADO batch size
//Flush a batch of inserts and release memory:
session.Flush();
session.Clear();
}
}
tx.Commit();
session.Close();
The usual implementation of buffered communications uses circular buffers, and you manage them with modulus arithmetic.
For languages that don't have bitwise operators, modulus can be used to get the lowest n bits of a number. For example, to get the lowest 8 bits of x:
x % 256
which is equivalent to:
x & 255
Cryptography. That alone would account for an obscene percentage of modulus (I exaggerate, but you get the point).
Try the Wikipedia page too:
Modular arithmetic is referenced in number theory, group theory, ring theory, knot theory, abstract algebra, cryptography, computer science, chemistry and the visual and musical arts.
In my experience, any sufficiently advanced algorithm is probably going to touch on one more of the above topics.
Well, there are many perspectives you can look at it. If you are looking at it as a mathematical operation then it's just a modulo division. Even we don't need this as whatever % do, we can achieve using subtraction as well, but every programming language implement it in very optimized way.
And modulu division is not limited to finding odd and even numbers or clock arithmetic. There are hundreds of algorithms which need this module operation, for example, cryptography algorithms, etc. So it's a general mathematical operation like other +, -, *, /, etc.
Except the mathematical perspective, different languages use this symbol for defining built-in data structures, like in Perl %hash is used to show that the programmer declared a hash. So it all varies based on the programing language design.
So still there are a lot of other perspectives which one can do add to the list of use of %.