>>18 EXPERT PROGRAMMERs use only unsigned integers, no floating points or other silly stuff like negative numbers.
Name:
Anonymous2007-09-05 18:51 ID:shW8/HmI
>>13
However if the code is just, like... bool isodd(int x) { return (x % 2) != 0; }
Then it ends up being compiled to exactly the same as bool mask_isodd(int x) { return x & 1; }
Still, something to know. When you need to remove that one division, hurr. After all it's not like L2 cache misses didn't cost about five or six divisions' worth of cycles already... oh snap.
Name:
Anonymous2007-09-05 19:05 ID:shW8/HmI
Also, just int blah(int x) { return x % 2; }
compiles, with optimization, to a move, a shift, a "lea", an and and a sub; that's an instruction sequence with a 5-cycle latency. Far less than a division, which you'd require for a generic remainder operation. Not to mention that processors these days can interleave those 5 instructions among other stuff given either enough free registers (exactly the same number as for a div tho) or decoders that're far enough ahead of the execution stream.
So yeah. With C, it's best to state your intent and let the compiler figure it out. Which is why the (x % 2) != 0 thing compiles to a simple and, or I suppose inside an if statement to a test insn.
Name:
Anonymous2007-09-05 20:24 ID:NvbhUvo4
irb(main):004:0> -10.0 & 1
NoMethodError: undefined method `&' for -10.0:Float
from (irb):4
from :0
Name:
Anonymous2007-09-05 20:24 ID:NvbhUvo4
irb(main):005:0> -10.0 % 2
=> -0.0
Name:
Anonymous2007-09-05 21:19 ID:eU+eCb50
>>22,23
Why are you using floats? Everyone's using ints.
Name:
Anonymous2007-09-05 22:58 ID:NvbhUvo4
>>24
The point is to show that modulo works on real numbers (which floats try to emulate) while & doesn't
>>25
You probably shouldn't be checking floats for parity anyway.
Name:
Anonymous2007-09-06 9:56 ID:UgSPcWk2
>>26
He's checking to see if the number is odd or even. As floating point numbers include integers too, it's a valid check.
Actually this makes me wonder - how do you determine if a fractional or irrational number is odd or even, or is it undefined?
Probably you'd have to specify if the whole number part is odd or even. e.g. PI is odd, e is even, 5/2 is even.
Name:
Anonymous2007-09-06 10:20 ID:Oey+rR6i
>>22 >>23
Why on earth would you consider optimizing for a shit-slow language? Seriously. Ruby's runtime evaluates SYNTAX TREES for fuck's sake. It doesn't even have freaking common subexpression elimination, or dead code elimination.
Name:
Anonymous2007-09-06 10:42 ID:Oey+rR6i
>>27
Checking whether a real number is odd or even depends solely on the integer part. Therefore the correct method is (((int)f) % 2) != 0, rather than fmodf(f, 2) >= 1.0f.