Berkeley CSUA MOTD:Entry 33385
Berkeley CSUA MOTD
 
WIKI | FAQ | Tech FAQ
http://csua.com/feed/
2025/07/08 [General] UID:1000 Activity:popular
7/8     

2004/9/7-8 [Computer/SW/Languages/C_Cplusplus, Computer/Theory] UID:33385 Activity:kinda low
9/7     what is the answer to a negative number modulo some positive
        number? is it that same negative number?
        \_ -1 % 4 = 3, -2 % 4 = 2, -5 % 4 = 3.  I think.
           \_ That's not what bc or mscalc.exe say, but MS Excel agrees w/you!
        \_ Ask Dr. Math: http://mathforum.org/library/drmath/view/52343.html
        \_ In mathematics, a mod b where b is positive always returns positive.
           In C and C++, the '%' operator is pronounced 'remainder' and the
           results of a % b if a is negative is implementation defined.
        \_ Also Wikipedia:  http://en.wikipedia.org/wiki/Modular_arithmetic
2025/07/08 [General] UID:1000 Activity:popular
7/8     

You may also be interested in these entries...
2014/1/14-2/5 [Computer/SW/Languages/C_Cplusplus] UID:54763 Activity:nil
1/14    Why is NULL defined to be "0" in C++ instead of "((void *) 0)" like in
        C?  I have some overloaded functtions where one takes an integer
        parameter and the other a pointer parameter.  When I call it with
        "NULL", the compiler matches it with the integer version instead of
        the pointer version which is a problem.  Other funny effect is that
        sizeof(NULL) is different from sizeof(myPtr).  Thanks.
	...
2013/4/9-5/18 [Computer/SW/Languages/C_Cplusplus, Computer/SW/Apps, Computer/SW/Languages/Perl] UID:54650 Activity:nil
4/04    Is there a good way to diff 2 files that consist of columns of
        floating point numbers, such that it only tells me if there's a
        difference if the numbers on a given line differ by at least a given
        ratio?  Say, 1%?
        \_ Use Excel.
           1. Open foo.txt in Excel.  It should convert all numbers to cells in
	...
2013/4/29-5/18 [Computer/SW/Languages/C_Cplusplus, Computer/SW/Compilers] UID:54665 Activity:nil
4/29    Why were C and Java designed to require "break;" statements for a
        "case" section to terminate rather than falling-through to the next
        section?  99% of the time poeple want a "case" section to terminate.
        In fact some compilers issue warning if there is no "break;" statement
        in a "case" section.  Why not just design the languages to have
        termination as the default behavior, and provide a "fallthru;"
	...
2012/7/19-11/7 [Computer/SW/Languages/C_Cplusplus] UID:54439 Activity:nil
7/19    In C or C++, how do I write the code of a function with variable
        number of parameters in order to pass the variable parameters to
        another function that also has variable number of parameters?  Thanks.
        \_ The usual way (works on gcc 3.0+, Visual Studio 2005+):
               #define foo(fmt, ...) printf(fmt, ##__VA_ARGS__)
           The cool new way (works on gcc 4.3+):
	...
2011/3/7-4/20 [Computer/SW/Languages/C_Cplusplus] UID:54056 Activity:nil
3/7     I have a C question.  I have the following source code in two identical
        files t.c and t.cpp:
                #include <stdlib.h>
                int main(int argc, char *argv[]) {
                  const char * const * p1;
                  const char * * p2;
	...
2011/2/5-19 [Computer/SW/Languages/C_Cplusplus] UID:54027 Activity:nil
2/4     random C programming/linker fu question.  If I have
        int main() { printf("%s is at this adddr %p\n", "strlen", strlen); }
        and soda's /proc/sys/kernel/randomize_va_space is 2 (eg; on)
        why is strlen (or any other libc fn) at the same address every time?
        \_ I don't pretend to actually know the right answer to this, but
           could it have something to do with shared libraries?
	...
2010/2/12-3/9 [Computer/SW/Languages/C_Cplusplus] UID:53708 Activity:nil
2/12    I need a way to make a really big C++ executable (~200MBs) that does
        nothing.  No static initialization either.  Any ideas?
        \_ static link in lots of libraries?
        \_ #define a   i=0; i=0; i=0; i=0; i=0; i=0; i=0; i=0; i=0; i=0;
           #define b   a a a a a a a a a a
           #define c   b b b b b b b b b b
	...
2009/9/28-10/8 [Computer/SW/Languages/C_Cplusplus] UID:53409 Activity:nil
9/28    http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html
        Java is #1!!! Followed by C, PHP, C++, Visual Basic, Perl,
        C#, Python, Javascript, then finally Ruby. The good news is
        Pascal is going waaaay back up!
        \_ C is still more popular than C++?  I feel much better about myself
           now.
	...
2009/8/7-14 [Computer/SW/Languages/C_Cplusplus, Computer/SW/Languages/Java] UID:53252 Activity:high
8/6     In C one can do "typedef int my_index_t;".  What's the equivalent in
        C#?  Thanks.
        \_ C#? Are you serious? Is this what the class of 2009 learn?
           \_ No.  I have to learn .NET code at work.  I am Class of '93.
           \_ python is what 2009 learns, see the motd thread about recent
              cal courses and languages
	...
2009/7/21-24 [Computer/SW/Languages/Java] UID:53168 Activity:moderate
7/20    For those who care btw, it looks like eclipse is now A Standard Tool
        at UCB ugrad cs, probably replaced emacs.  Furthermore, people get
        angry at seeing Makefiles, (since eclispe takes care of that).  I
        guess it's just a sign of the times.
        \_ The more people at my work use eclipse the less the code is
           managable in emacs.  I'm not sure which application's fault
	...
2012/8/30-11/7 [Computer/SW/Apps, Computer/SW/Unix] UID:54470 Activity:nil
8/30    Is wall just dead? The wallall command dies for me, muttering
        something about /var/wall/ttys not existing.
        \_ its seen a great drop in usage, though it seems mostly functional.
            -ERic
        \_ Couldn't open wall log!: Bad file descriptor
           Could not open wall subscription directory /var/wall/ttys: No such file or directory
	...
2011/11/20-2012/2/6 [Computer/Companies/Apple, Computer/SW/Unix] UID:54237 Activity:nil
11/20   Are there tools that can justify a chunk of plain ASCII text by
        replacing words with words of similar meaning and inserting/removing
        commas into the text?  I received a 40-line plain text mail where
        all the lines are justified on left and right.  Every word and comma
        is followed by only one space, and every period is followed by two
        spaces.  The guy is my kid's karate instructor which I don't think is
	...
2011/10/26-12/6 [Computer/SW/Unix] UID:54202 Activity:nil
10/24  What's an easy way to see if say column 3 of a file matches a list of
       expressions in a file? Basically I want to combine "grep -f <file>"
       to store the patterns and awk's $3 ~ /(AAA|BBB|CCC)/ ... I realize
       I can do this with "egrep -f " and use regexp instead of strings, but
       was wondering if there was some magic way to do this.
       \_ UNIX has no magic. Make a shell script to produce the ask or egrep
	...
Cache (8192 bytes)
mathforum.org/library/drmath/view/52343.html
Math Mod Function and Negative Numbers Date: 04/28/2000 at 11:17:09 From: Anne Subject: Using the mod() function with negative numbers I work in IT - Technical Support. I am trying to sort out a problem for a user who is using the MOD() function in Excel 97 as follows: =MOD(-340,60) He thinks it should return a value of 40, but it returns a value of 20. It returns a value of 40 if we do the following: =MOD(340,60) Now I am wondering why the negative sign makes a difference. You can see from my age that it was years ago that I had math, and I was very good at it. But I cannot remember how negative numbers work in division. Anne Date: 04/28/2000 at 12:57:10 From: Doctor Peterson Subject: Re: Using the mod() function with negative numbers Hi, Anne. There are different ways of thinking about remainders when you deal with negative numbers, and he is probably confusing two of them. The mod function is defined as the amount by which a number exceeds the largest integer multiple of the divisor that is not greater than that number. In this case, -340 lies between -360 and -300, so -360 is the greatest multiple LESS than -340; we subtract 60 * -6 = -360 from -340 and get 20: -420 -360 -300 -240 -180 -120 -60 0 60 120 180 240 300 360 --+----+----+----+----+----+----+----+----+----+----+----+----+----+-- | | | | -360| |-340 300| |340 |=| |==| 20 40 Working with a positive number like 340, the multiple we subtract is smaller in absolute value, giving us 40; but with negative numbers, we subtract a number with a LARGER absolute value, so that the mod function returns a positive value. This is not always what people expect, but it is consistent. If you want the remainder, ignoring the sign, you have to take the absolute value before using the mod function. math/ Date: 05/02/2000 at 04:58:50 From: Norwich CC Network Services Subject: Re: Using the mod() function with negative numbers Thanks very much for sorting this out. I had worked out how it was arriving at the result, but did not know whether it was correct. We had also tried it in Lotus 1-2-3 and the result given was -40, which was what the user expected. Anne Date: 05/02/2000 at 17:16:19 From: Doctor Peterson Subject: Re: Using the mod() function with negative numbers Hi, Anne. It occurs to me that I don't quite want to leave you trusting Excel too much. A comment I had considered making before was that a program may often use its own definitions for functions like this, and apparently Lotus proves my point that "mod" can be taken in different ways. You should always go by the manual, not by what a mathematician says. here's a copy of an answer I gave to someone who asked about its handling of -a^b: =========================================================== The proper rule is that negation has the same precedence as multiplication and division. asp It doesn't claim that their rule agrees with the mathematical world, only that they make their own standards, and don't have to agree with anyone: This behavior is by design of Microsoft Excel. Microsoft Excel uses an order of calculation to evaluate operators in formulas. The order of evaluation of operators dictates that a minus sign used as a negation operator (such as -1) is evaluated before all other operators. Because of this order, the formula =-1^2 represents the value -1 squared, and returns the value 1, a positive value. Note that this has been the standard method for evaluating formulas since the first version of Microsoft Excel. NOTE: This order of operation is different from the order of operation in Lotus 1-2-3. What I suspect is that the programmers were accustomed to the C language, in which unary operators such as negation have higher precedence than any binary operator; there is no exponent operator in C When they added the exponent operator, they may simply have forgotten that it should have higher precedence, or they may have found it was easier to program this way. Once the rule became established, they couldn't change it and make customer's programs fail. There are many other instances where calculators or software make their own rules; sometimes this is because of limitations of their interface, sometimes because of a misguided desire to "improve" the rules. In any case, we can't use any piece of software as our guide to mathematical practice, and students should be taught not to confuse the rules of a particular program with those of math. We wouldn't want Microsoft to be making these decisions for us anyway, would we? math/ Date: 05/03/2000 at 08:53:33 From: Norwich CC Network Services Subject: Re: using the mod() function with negative numbers Thanks for that! Anne Date: 07/05/2001 at 13:58:23 From: A H Banen Subject: Mod Function and Negative Numbers Dear Dr. Peterson, Concerning the topic "Mod Function and Negative Numbers," I found it strange you did not refer to the simple rule concerning integer division and modulo calculation: Given the integer numbers A and B (where B cannot be equal to zero), the following holds: A = ( A DIV B ) * B + A MOD B eg for A = 340 and B = 60 A = ( 340 DIV 60 ) * 60 + ( 340 MOD 60 ) => A = ( 5 ) * 60 + 40 => A = 340 Also, when A = -340 and B = 60 A = ( -340 DIV 60 ) * 60 + ( -340 MOD 60 ) A = ( -5 ) * 60 + ( -40 ) => A = -340 From this can be derived that MOD(-340, 60) should have been -40 Sincerely, Andre Banen Date: 07/05/2001 at 16:17:04 From: Doctor Peterson Subject: Re: Mod Function and Negative Numbers Hi, Andre. You're right that this relation is relevant to the question; But it only proves what MOD should do _if_ we know how DIV is defined; that is, it is a statement of consistency between the mod function and the direction of integer truncation. You're _assuming_ truncation toward zero, so that -340/60 gives -5. But in Excel, we see that the relation looks like this: A = ( -340 DIV 60 ) * 60 + ( -340 MOD 60 ) -340 = -6 * 60 + 20 This is perfectly consistent if their integer division truncates toward -infinity rather than toward zero, so that -340/60 is taken to be -6. And that's just what I said, using words rather than the formula: The mod function is defined as the amount by which a number exceeds the largest integer multiple of the divisor that is not greater than that number. In this case, -340 lies between -360 and -300, so -360 is the greatest multiple LESS than -340; Here's a more complete answer: Computer languages and libraries are notoriously inconsistent, or at least unmathematical, in their implementation of "mod" for negative numbers. There are several ways it can be interpreted in such cases, and the choice generally made is not what a mathematician would probably have made. The issue is what range of values the function should return. Mathematically, we define "modulo" not as a function, but as a relation: any two numbers a and b are congruent modulo m if (a - b) is a multiple of m If we want to make a function of this, we have to choose which number b, of all those that are congruent to a, should be returned. html The value of b, where a=b (mod m), taken to be nonnegative and smaller than m Unfortunately, this statement about FORTRAN, and implicitly about the many languages that have inherited their mathematical libraries from FORTRAN, including C++, is not quite true where negative numbers are concerned. The problem is that people tend to think of modulus as the same as remainder, and they expect the remainder of, say, -5 divided by 3 to be the same as the remainder of 5 divided by 3, namely 2, but negated, giving -2. We naturally tend to remove the sign, do the work, and put the sign back on, because that's how we divide. In other words, we expect to truncate toward zero for both positive and negative numbers, and have the remainder be what's left "on the outside," away from zero. More particularly, computers at least since the origin of FORTRAN have done integer division by "truncating toward zero," so that 5/2 = 2 and -5/2 = -2, and they keep their definition of "mod" or "%" consistent with this by requiring that (a/b)*b + a%b = a so that "%" is really defined as the remainder of integer division as defined in the language. Because FORTRAN defined division and...
Cache (5272 bytes)
en.wikipedia.org/wiki/Modular_arithmetic
clock arithmetic', where numbers 'wrap around' after they reach a certain value (the modulus). For example, when the modulus is 12, then any two numbers that leave the same remainder when divided by 12 are equivalent (or "congruent") to each other. The collection of all such numbers is a congruence class. As explained below, one can add such congruence classes to get another such congruence class, subtract two such classes to get another, and multiply such classes to get another. Gauss two centuries ago, still used by mathematicians, and suitable for theoretical mathematics, and * a newer one adhered to by computer scientists and perhaps more suitable for computing. A third sort of usage by mathematicians is quite different from these, but does not conflict with them because it deals with different subject matter. It evolved ultimately from the usage introduced by Gauss in 1801. One says: "63 is congruent to 83, modulo 10," or "63 and 83 are congruent to each other, modulo 10." "Modulo" is usually abbreviated to "mod" in speaking, just as in writing. The mathematical usage parses the phrase differently from the computing usage. edit The newer convention, used in computing According to the newer convention, in general, a mod n is the remainder on integer division of a by n Depending on the implementation, the remainder r is typically constrained to 0 < |r| < |n|, with a negative remainder only resulting when n < 0 The difference in conventions is not very serious, in fact; programming languages have a mod() function or similar, expressed as mod(a,n), for example. Some also support expressions that use "%" as a modulo operator, such as a % n a mod n can be calculated by using equations, in terms of other functions. Differences may arise according to the scope of the variables, which in common implementations is broader than in the definition just given. Python, can be described in terms of the floor function floor, the greatest integer less than or equal to z: mod(a,n) = a - n floor(a n) This definition allows for a and n to be typed as integers or rational numbers. The fundamental arithmetic operations performed by most computers are actually modular arithmetic, where the modulus is 2^b (b being the number of bits of the values being operated on). If R is a commutative ring, and I is an ideal of R, then the elements a and b of R are congruent modulo I if a - b is an element of I As with the ring of integers, this turns out to be an equivalence relation, and addition and multiplication become well-defined operations on the factor ring R/I. edit Another "computing" usage An implied meaning of modulo in computing contexts is "valid up to this value." For example, "addition is modulo 1,000" means that the addition operation being described provides valid answers until the sum goes beyond 1,000. bits, the values that can be represented range from 0 to 255. When an addition (or multiplication, or whatever) results in a number above this cutoff, the typical behavior is for the values to wrap around. For example, in the 8-bit positive integer situation, 255 + 1 = 0 This computer is therefore described as "modulo 256". Furthermore, some computers do different operations with different bit representations. So although the storage of integers may be 8-bit ("modulo 256"), the addition of integers may be 12-bit ("modulo 4096"), or anything else. Thus individual operations can also be described as "modulo x". In the case of signed (positive and negative) integers, or floating point numbers, the wrap around effect is more complicated, and is not always perfectly analogous to the formal mathematical modulo. edit More general use of the word modulo by mathematicians To say that any two things are the same "modulo" a third thing means, more-or-less, that the difference between the first two is accounted for or explained by the third. up to concept is often talked about this way, using modulo as a term alerting the hearer. In mathematics, this admits various precise definitions. In particular, two members of a ring or an algebra are congruent modulo an ideal if the difference between them is in the ideal. The use of the term in modular arithmetic is a special case of that usage, and that is how this more general usage evolved. edit Slang use of the word modulo Mathematicians speaking of things non-mathematical still say "A is the same as B modulo C" when they mean A is the same as B except for differences accounted for by C But in such non-mathematical contexts, the phrase may not admit any very precise definition. Consequently mathematicians and computer scientists often use the phrase in an informal or even jocular way. Some users of the term either lack this theoretical viewpoint or else ignore it, and use the word "modulo" more-or-less synonymously with the preposition except. "The two students performed equally well on the exam, modulo some minor computational mistakes." "This code is finished modulo testing" - means "this code is finished except for testing". Since testing is generally considered quite important, whereas in mathematics the use of modular arithmetic generally ignores the difference between modulo-equal numbers, use of a phrase like this might be deliberate understatement.