• (cs) in reply to no name
    no name:
    bstorer:
    I sense sarcasm in your statement... You can't just assume that int is 32-bits. What if you have a one bit integer? Then you need BigInteger for the 2.
    But, it looks like we are dealing with Java, so ints are always 32 bits, no matter what the underlying architecture.

    If I remember right, even in C they have to be at least 7 bits.

    Seven bits? Seven???

    Has anyone considered what happens if a bit has to be large enough to allow values of 0, 1 and FILE_NOT_FOUND?

    Anyway, here's my two bits, for what it's worth: 11

  • iToad (unregistered) in reply to katre
    katre:
    Jon Skeet:
    I'm surprised that there have been this many comments without someone pointing out that

    if ((x%2)==0) is the same as if ((x&1)==0)

    but the latter is marginally faster. Less readable (arguably), and bound to make no significant difference at all, but that doesn't usually stop the comments :)

    Hmm, it's less readable, and it's the kind of simple optimization the compiler or the JVM can do? I'll definitely go change all my code, right now!

    ((x % 2) == 0) implies that you are directly checking to see whether the value of x is evenly divisible by 2 (is it even or odd?)

    ((x % 1) == 0) implies that you are checking to see whether the low bit of the binary value is set to 1. By the way, if the bit is set/not set then the value is even or odd.

    The first version directly shows what you intend to test. the second version is a little more indirect...

  • (cs)

    Whenever I'm trying to make alternating-row styles, I use something like:

    string NextRowStyle() { static bool e = true; e = !e; return e ? "even" : "odd"; }

  • rbonvall (unregistered) in reply to iToad
    iToad:
    ((x % 2) == 0) implies that you are directly checking to see whether the value of x is evenly divisible by 2 (is it even or odd?)

    ((x % 1) == 0) implies that you are checking to see whether the low bit of the binary value is set to 1. By the way, if the bit is set/not set then the value is even or odd.

    x % 1 is always 0, so your test is superfluous </pedantic>

    Besides, instead of

    if ((x & 1) == 0) ...
    it is better to
    !(x&1)?...:...;
    </real-programmer>

  • csyers (unregistered) in reply to foxyshadis

    Err, me thinks you missed the 2^32 bits part.

  • Reed (unregistered)

    string NextRowStyle() { static bool e = true; e = !e; return e ? "even" : "odd"; }

    Beware using static!! Can result in some rather subtle and mysterious errors in a multithreaded program.

  • (cs) in reply to Reed
    Reed:
    string NextRowStyle() { static bool e = true; e = !e; return e ? "even" : "odd"; }

    Beware using static!! Can result in some rather subtle and mysterious errors in a multithreaded program.

    Alright.

    string NextRowStyle(ref bool IsEven) { IsEven = !IsEven; return IsEven ? "even" : "odd"; }

  • Asd (unregistered) in reply to rbonvall
    rbonvall:
    Besides, instead of
    if ((x & 1) == 0) ...
    it is better to
    !(x&1)?...:...;
    </real-programmer>
    A real programmer might remember this is a Java program...

    Similarly no static local variables or refs, so string NextRowStyle(ref bool IsEven)

    would have to become String NextRowStyle(boolean[] IsEven) { IsEven[0] = !IsEven[0]; return IsEven[0] ? "even" : "odd"; }

  • (cs) in reply to Asd
    Asd:
    rbonvall:
    Besides, instead of
    if ((x & 1) == 0) ...
    it is better to
    !(x&1)?...:...;
    </real-programmer>
    A real programmer might remember this is a Java program...

    Similarly no static local variables or refs, so string NextRowStyle(ref bool IsEven)

    would have to become String NextRowStyle(boolean[] IsEven) { IsEven[0] = !IsEven[0]; return IsEven[0] ? "even" : "odd"; }

    Thanks for translating to Java--I've never done any serious work in Java, so I didn't want to butcher it in trying. Most of my programming for the web is in C#, VB, PHP, and Ruby, with a good dollop of C++ experience for non-Web apps. Again, thank you.
  • Aaron (unregistered) in reply to Anonymous commie
    Anonymous commie:
    Aaron:
    Funny. Fortunately for our users, these tables aren't edited or dumped directly!
    In this case, there is no need for color coding every other row in HTML, is it?(*)
    Aaron:
    Although one client did ask explicitly for raw data totalling a few million rows - can't imagine what they intend to do with it.
    I remember legends told about Real Programmers in the Old Days that could read hex dumps, which was then basically a pile of pyjama paper - some inches high (or multiple of 5 centimeters - lets not get started on the "metrics suck!" topic again, please) - filled with hex numbers. Maybe your client was a Real Programmer.
    People usually deal with a graphical representation of that data if they have to deal with it at all, but sometimes they'll have to look at maybe a hundred rows and in that case, yes, they are color coded. :-)

    I'm pretty sure said client isn't actually printing the data (I sincerely hope not!). Maybe they intended to analyze it in Excel (not bloodly likely given its row limit) or their own database (possible, but a pointless waste of bandwidth since we've spent years on this and could just be providing the analytics they want).

    But hey, boys will be boys. If they like playing with raw data then who am I to say no. I just hope their Real Program™ accepts (SQL) bigints!

  • Ted (unregistered)

    I hope that, after Eric made his change, he checked the REST of the system to see if his reversal of the program's meaning of "even" and "odd" (which, granted, was wrong to begin with) had any impact on behaviour.

    Too often, in systems like this, a small bug like that becomes an integral part of the structure that holds the whole thing up. Like, if the system needs for "0" to be "odd" in order to jump-start some counter that gets the whole thing going, or some such.

  • (cs)

    Also, what if (index == 0)?

  • PC Paul (unregistered) in reply to csyers
    csyers:
    Err, me thinks you missed the 2^32 *bits* part.

    You mean Java has a class for handling 'arbitrarily large' values, but puts a 2^(2^32)-1 upper bound on it? Pah!

    I wanted to use big numbers!

    How many decimal digits has 2^(2^32)-1 got, anyway?

  • Botzinger Gulm (unregistered) in reply to PC Paul
    PC Paul:
    How many decimal digits has 2^(2^32)-1 got, anyway?

    About 1292914005.11488.

    Is that enough?

    It's more than 640k.

    Or did you mean 2^(2^32-1)?

  • Paul (unregistered)
    return ( (evenRow.equals("0")) ? "odd" : "even" );

    Alex, you have a typo in the WTF: too many closing parentheses.

  • Kyle (unregistered) in reply to dhromed
    dhromed:
    new BigInteger("2")

    I have absolutely no idea what could possibly go through the mind of the coder who typed this.

    Perhaps java's BigInteger mod method only takes one type of parameter ... oh say, another BigInteger?

    Granted, the use of BigInteger in this situation is quite unnecessary but given that it is used, do you have another way to divide a BigInteger?

  • mcguire (unregistered) in reply to Anonymous commie
    Anonymous commie:
    Definitively. But I would personally hate to browse through a web page with more than 2147483648 rows, and I think I would still hate it in the next century.

    Probably; I think you'd still be browsing that same page. If you hate it now, you'll still hate it then.

  • (cs) in reply to iToad
    iToad:
    katre:
    Jon Skeet:
    I'm surprised that there have been this many comments without someone pointing out that

    if ((x%2)==0) is the same as if ((x&1)==0)

    but the latter is marginally faster. Less readable (arguably), and bound to make no significant difference at all, but that doesn't usually stop the comments :)

    Hmm, it's less readable, and it's the kind of simple optimization the compiler or the JVM can do? I'll definitely go change all my code, right now!

    ((x % 2) == 0) implies that you are directly checking to see whether the value of x is evenly divisible by 2 (is it even or odd?)

    ((x % 1) == 0) implies that you are checking to see whether the low bit of the binary value is set to 1. By the way, if the bit is set/not set then the value is even or odd.

    The first version directly shows what you intend to test. the second version is a little more indirect...

    Excuse me? How is x%2 any more/less readable than x&1?

    By your argument x%2 implies you are directly checking to see if x is evenly divisible by 2. By the way, if it is evenly divisible by 2 it is even. x&1 imples you are checked to see whether the number is even because the last bit is set/unset.

    The second version directly shows what you intend to test. The first version is a little more indirect...

  • (cs)

    This reminds me of a former coworker. My friends an I called him Mr Int64. He insisted on using int64's, and claims he has done so since the early 90s.

    Int64 has some uses. For example if you are counting the grains of sand on the beach. And if you are on an 64 bit machine, its probably fine and dandy to use Int64. But on a 32 bit machine, for day to day processing, the word size of the machine is just fine.

    We first got into the argument, when I noticed he was using Int64 for pixel location on the monitor. Apparently he didn't realize that a montior would have to be like a mile(or some insane size) wide before 32 bits wasn't large enough.

    But one day he turned to me, with a huge smile. "I know how to overflow int32." I had to know what he thought was too big, so I asked. "Well what if you wanted to store all the possible colors?" "Well", I responded... "we use 32 bit color, so..." "Hmm yeah, but what if you wanted all the possible transparencies as well" "Again, its 32 bit color..."

    Before he left, he came up with one more reason. Our original prototype was using an int for an ID. We would probably only have 4 or 5 objects, maybe a dozen, with a max of a hundred or so... Ahhh but perhaps we should use Int64, because if we implement this one feature we might have 10 million!

  • justbrowsing (unregistered) in reply to Carsten Otto

    Why not use BigInteger.ONE + BigInteger.ONE for your purposes?

  • Matt (unregistered) in reply to dhromed
    dhromed:
    new BigInteger("2")

    I have absolutely no idea what could possibly go through the mind of the coder who typed this.

    I've seen someone use a calculator to work out 1 * 1

  • (cs) in reply to justbrowsing
    justbrowsing:
    Why not use BigInteger.ONE + BigInteger.ONE for your purposes?
    Because that's not as much fun as BigInteger.ONE.shiftLeft(1). Or even better, BigInteger.ONE.nextProbablePrime ().
  • TACOS! (unregistered) in reply to Moogle
    Moogle:
    Bwahahah, I should probably submit this as a full WTF on its own, it's so bad. (Except it's a student project, so not so surprising.)

    I and a friend had a CS theory class where we had to write a bigint class to do RSA encryption - we couldn't use the native bigint in whatever language we chose. I originally wrote mine in C, but as the deadline neared and my memory usage exploded, I realized it would be faster to rewrite in java than to fix the memory leaks. I ended up with a pretty good bigint class that would do math calculations on 32 bit chunks, calculating overflows and everything.

    I had been keeping tabs on my friends progress, but I didn't quite pay enough attention to understand what he was up to until the very end. I forget what language he used (java also I guess), but apparently since the TAs said they'd only be testing 512 bit keys, he was statically allocating 1024 bits (to hold multiplications of two 512 bit numbers). So aside from not being an arbitrary sized bigint, it used the same memory whether it is was holding 2 or 2e200.

    It was only after the due date that he explained, to my great horror, that he was using 32 bit integers to hold his bits.

    1024 32 bit ints to hold each individual 1 or 0 ...

    I have seen A LOT of similar stuff at my university. How about a c++ class (For a game none the less) containing a quadtree of which 2/3rds of the code were simply crud that did nothing. And the rest of the code were not too good. How about accessing arrays with negative numbers? AND then using the return values of that for the functionality! Aaargh!!!

    Or the Object class that had the getRotationMatrix() method, that returned a matrix from inside the class that was named rotation. But it was only ever initialized, not used for the rotation that that class handled. So when you called that metod, all you ever could get was an identity matrix. AND the math library used had Matrix.Identity(). So getting identity matrices was easy. Now, when I spotted that method, I fixed it, because I needed such a funktion. With all hell breaking lose because their game, built on this engine (We were making a game as well with it) actually used that method. WTF? If they need an identity matrix, use the math lib.

    Now, I could keep going for, oh, say, half an hour to an hour with the atrocities that engine contained. But I wont. ;)

  • Marcin (unregistered)

    The real WTF is that they did not use an iterative method, which would be approximately seven times faster than this one.

  • (cs) in reply to Marcin
    Marcin:
    The real WTF is that they did not use an iterative method, which would be approximately seven times faster than this one.
    What's an iterative method? Based on the meaning of iterative, I'd say their function fits as well as any other, so I must be missing some specialized meaning.
  • panzi (unregistered)

    I do not know if this works in Java the same (but I think it does), but in C/C++ I (would) use:

    ((index & 1) ? "odd" : "even")

    Bit operations are faster then a modulo-DIVISION! (And because it's a index, I can assume it's always positive, can't I?)

  • Khorne (unregistered) in reply to Jon Skeet
    Jon Skeet:
    if ((x%2)==0) is the same as if ((x&1)==0)

    Not true when x is negative.

  • Diego (unregistered)

    The real reason of jealousy of computer scientists is they don't know how to do math properly. Rare universities teach proper math to computer science students :-(

  • Look at me! I'm on the internets! (unregistered) in reply to clevershark
    clevershark:
    ( (evenRow.equals("0")) ? "odd" : "even" );

    WTF... this produces exactly the wrong answer every time!

    That function could be added to the Paula Bean...

    I actually think this produces the intended result. index == 0 --> 1st Row (odd) index == 1 --> 2nd Row (even)

    Remember that the rest of the world starts counting at 1, not zero.

  • Dark Shikari (unregistered)

    BigInteger is nice but its abominably slow for what it does...

    A friend of mine was futzing around with Java and coded a basic RSA algorithm in Java. It was taking minutes to encrypt even the smallest message.

    So I showed him the light of GMP Bignum.

    It now goes over a million times faster.

  • Jonathan (unregistered) in reply to TACOS!
    TACOS!:
    And the rest of the code were not too good. How about accessing arrays with negative numbers?
    I suppose if you really wanted to use negative index values you could set up an array in C that would let you do so safely...

    Allocate an array, then assign the mem address of the middle of the array to a pointer that matches the array type, and proceed to treat the pointer like an array.

    (After all, it's C)

    Something like

     int temp[101];
     int *negarray;
     negarray = &temp[51]; //should be able to address from 
                     //negarray[-50] to negarray[50] safely
     
     temp[52]=6;
     temp[51]=4;
     temp[50]=2;
    
     if ( 2 == negarray[-1] )
       printf("Negative array indices work.  Scary");
     else
       printf("I seem to have forgotten how to write in C");
    
  • shrndegruv (unregistered)

    If an index into an html table needs more than 32 bits, I dont think how you get odd or even really matters, because there are greater problems....

  • mrboyblue (unregistered) in reply to chrismcb
    chrismcb:
    Excuse me? How is x%2 any more/less readable than x&1?

    By your argument x%2 implies you are directly checking to see if x is evenly divisible by 2. By the way, if it is evenly divisible by 2 it is even. x&1 imples you are checked to see whether the number is even because the last bit is set/unset.

    The second version directly shows what you intend to test. The first version is a little more indirect...

    x&1 is indirect because you're testing the representation of the number rather than the number itself. If the representation changes or isn't what you expect (like negative numbers as pointed out above) then the test could fail, but x % 2 will always work in any system (or on paper if you're one of those mathematician peoples).

  • (cs) in reply to Moogle
    Moogle:
    It was only after the due date that he explained, to my great horror, that he was using 32 bit integers to hold his bits.

    Yeah. A Real Programmer would have implemented it in LISP, and used a cons cell for each bit.

    (A Really Real Programmer would have implemented it in a single line of APL. No point in wasting time with inferior tools.)

    -- Michael Wojcik

  • smugness (unregistered) in reply to mrboyblue
    mrboyblue:
    x&1 is indirect because you're testing the representation of the number rather than the number itself. If the representation changes or isn't what you expect (like negative numbers as pointed out above) then the test could fail, but x % 2 will always work in any system (or on paper if you're one of those mathematician peoples).

    They are both indirect. Why don't you just ask the number if is even or odd?

    ^ (x isOdd) ifTrue: [ 'odd' ] ifFalse: [ 'even' ].

  • Rich (unregistered) in reply to Khorne
    Khorne:
    Jon Skeet:
    if ((x%2)==0) is the same as if ((x&1)==0)

    Not true when x is negative.

    I'm pretty sure it is

    -5%2=1 -5= 1[...]111011 -5&1=1

    Rich

  • Rich (unregistered) in reply to panzi
    panzi:
    I do not know if this works in Java the same (but I think it does), but in C/C++ I (would) use:

    ((index & 1) ? "odd" : "even")

    Bit operations are faster then a modulo-DIVISION! (And because it's a index, I can assume it's always positive, can't I?)

    char opts[]="even\0\0\0\0odd\0" return opts+((index&1)<<3)

    I win!

    (Cept this is way late).

    Rich

  • esrever_otua (unregistered) in reply to Scooter Libby
    Scooter Libby:
    bstorer:
    snoofle:
    Duston:
    Anonymous commie:
    Definitively. But I would personally hate to browse through a web page with more than 2147483648 rows, and I think I would still hate it in the next century.

    But what about the people with 2147483649 messages in their inbox?

    There are days that it feels like I have 2147483649 messages in my inbox. Is there a macro that in one click, I can use to send them all back with a common message?
    There's the "Select All, Delete" option. Will that work?

    No. It was implemented with a signed short.

    How did you know?
  • Jeltz (unregistered) in reply to katre
    katre:
    Jon Skeet:
    I'm surprised that there have been this many comments without someone pointing out that

    if ((x%2)==0) is the same as if ((x&1)==0)

    but the latter is marginally faster. Less readable (arguably), and bound to make no significant difference at all, but that doesn't usually stop the comments :)

    Hmm, it's less readable, and it's the kind of simple optimization the compiler or the JVM can do? I'll definitely go change all my code, right now!

    No, the JVM cannot do that optimisation since posisble values of x%2 are 1, 0, -1, while x&1 can only be 1, 0. How the hell would the JVM know that x is always positive? Last time I checked Java had no unsigned integers.

    In other languages where % is "real" mathematical modulo the optimisation would be possible.

  • Jeltz (unregistered) in reply to Rich
    Rich:
    Khorne:
    Jon Skeet:
    if ((x%2)==0) is the same as if ((x&1)==0)

    Not true when x is negative.

    I'm pretty sure it is

    -5%2=1 -5= 1[...]111011 -5&1=1

    Rich

    In Python, yes but in almost every other language no.

    -5%2 = -1

    in most programming languages, Java, C99 and PHP included.

    See the table in this Wikipedia article for some examples.

    http://en.wikipedia.org/wiki/Modulo_operation

  • Kuba (unregistered) in reply to infidel
    infidel:
    One of the neatest features that sold me on Python is the way it lets you work with integers of any size:

    10 ** 100 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L

    $ sbcl

    • (expt 10 100)

    10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

    Mind ya, this would look the same on some LISP 30 years ago.

    Wikipedia: M-expression:
    Several other languages, such as Dylan and Python, borrow heavily from Lisp, but use an ALGOL-like syntax that differs from both S-expressions and M-expressions.
    There's your progress.

    Cheers, Kuba

  • Kuba (unregistered) in reply to TACOS!
    TACOS!:
    How about accessing arrays with negative numbers?

    Umm, you meant like this?

    /* 
    Return last n characters of a null-terminated string.
    Beware that this is O(N), where N is string length.
    Use a Pascal string if you need this functionality often
    */
    const char * last(const char * string, unsigned int n)
    {
      register const char * p = string; // yeah, stupid compiler
      while (*p) ++ p;
      return &p[-n]; // or p-n
    }
    

    Perfectly valid C (and C++!), and this is production code.

    Cheers, Kuba

  • Ryan S (unregistered)

    This scares me:

    My class just finished a make-a-BigInt assignment a couple weeks ago... figure about now you've got many of them graded... and I know my teacher hates most of us...

    I wonder...

    (Take note that my name is not Eric)

  • Cliff (unregistered)

    A maths-professor friend of mine commented the other day after I got caught by a rounding error, "Why is it that programmers don't use rationals?"

    I told her, "Because we don't know what they are."

    After several hours of instruction (it felt like being back at school), I once again understood GDC and LCM and had written a library. It's amazing how much easier mathematical programs have become since then.

    Cliff.

  • hg (unregistered) in reply to TACOS!
    TACOS!:
    Moogle:
    Bwahahah, I should probably submit this as a full WTF on its own, it's so bad. (Except it's a student project, so not so surprising.)

    I and a friend had a CS theory class where we had to write a bigint class to do RSA encryption - we couldn't use the native bigint in whatever language we chose. I originally wrote mine in C, but as the deadline neared and my memory usage exploded, I realized it would be faster to rewrite in java than to fix the memory leaks. I ended up with a pretty good bigint class that would do math calculations on 32 bit chunks, calculating overflows and everything.

    I had been keeping tabs on my friends progress, but I didn't quite pay enough attention to understand what he was up to until the very end. I forget what language he used (java also I guess), but apparently since the TAs said they'd only be testing 512 bit keys, he was statically allocating 1024 bits (to hold multiplications of two 512 bit numbers). So aside from not being an arbitrary sized bigint, it used the same memory whether it is was holding 2 or 2e200.

    It was only after the due date that he explained, to my great horror, that he was using 32 bit integers to hold his bits.

    1024 32 bit ints to hold each individual 1 or 0 ...

    I have seen A LOT of similar stuff at my university. How about a c++ class (For a game none the less) containing a quadtree of which 2/3rds of the code were simply crud that did nothing. And the rest of the code were not too good. How about accessing arrays with negative numbers? AND then using the return values of that for the functionality! Aaargh!!!

    Or the Object class that had the getRotationMatrix() method, that returned a matrix from inside the class that was named rotation. But it was only ever initialized, not used for the rotation that that class handled. So when you called that metod, all you ever could get was an identity matrix. AND the math library used had Matrix.Identity(). So getting identity matrices was easy. Now, when I spotted that method, I fixed it, because I needed such a funktion. With all hell breaking lose because their game, built on this engine (We were making a game as well with it) actually used that method. WTF? If they need an identity matrix, use the math lib.

    Now, I could keep going for, oh, say, half an hour to an hour with the atrocities that engine contained. But I wont. ;)

  • Jim T (unregistered)

    Ok, pedantic killjoy necromancer at work here, but it's actually a fairly reasonable function to come up with given the circumstances:

    Java learned by reading docs as required on the fly not from a boring ground up textbook or course. Hence, the % (mod) operator has been completely missed (or entirely forgotten in the mists of time). Need to do a Mod, check javadocs, only 1 Mod method exists! It's on a BigInteger, oh man! Here we go, converting that int to a BigInt so that I can access the damn Mod method. Oh look, it only takes another BigInt! I can't even pass 2 in. Oh those BigInt constructors are pretty damn obtuse. Ah, a string based constructor that will just parse the string, guess I'll have to do that. I'm not creating a new BigInt("0") object to see if it's zero or not, once was enough, I'll just return the result as a string and check that. See I'll have an additional static "0" string which would get parsed every time anyway, this would probably actually be faster. The fact that it returns "odd" for even numbers would be completely ignored as all that's really needed is alternating classes, which is what this provides.

    So the whole debacle comes from not knowing about the builtin % operator. Int doesn't have a "mod" method. BigInt does, making it orders of magnitude more discoverable.

    Perhaps at least some of the problem can be put down to documentation being method heavy, whereas builtin operators need to be explicitly searched for in a different place entirely. Perhaps if the int documentation included "operator%" or something, then at least you'd only end up with return value.operator%(2) == 0?"odd":"even"; (sic)

    Umm, should I be scared that I can reproduce a logical flow to generate this method so easily? Should I be more scared that I care enough to post this after this thread died so long ago?

  • Spock (unregistered)

    Does it really have to do with 32/64 etc. bits ? just take LSB of the number and if it is 1 then its an even number and if it is 0 then it is odd. Or take the number on the unit's place and divide it by 2 if remainder is 0 it is even if remainder is odd the number is even !

Leave a comment on “Big Math, Little Snippet ”

Log In or post as a guest

Replying to comment #126647:

« Return to Article