Simple math question

What's the quickest way to determine if an int is an even number
2,4,6,8...
Anything such as int.even or int.odd returning true/false? I want to
test the length of an array and add one element to it if it has an odd
number of elements.

Thank you!

···

--
Posted via http://www.ruby-forum.com/.

What's the quickest way to determine if an int is an even number 2,4,6,8...
Anything such as int.even or int.odd returning true/false? I want to test the length of an array and add one element to it if it has an odd number of elements.

class Integer
  def even?
    (self & 1) == 0
  end
end

Hope this helps,

Bill

···

From: "Brad Tilley" <rtilley@vt.edu>

number % 2 == 0 #even
number % 2 == 1 #odd

Mark

···

On 10/25/06, Brad Tilley <rtilley@vt.edu> wrote:

What's the quickest way to determine if an int is an even number
2,4,6,8...
Anything such as int.even or int.odd returning true/false? I want to
test the length of an array and add one element to it if it has an odd
number of elements.

Thank you!

--
Posted via http://www.ruby-forum.com/\.

--
Mark Van Holstyn
mvette13@gmail.com
http://lotswholetime.com

You can determine if a number is odd by doing this:

class Fixnum
  def odd?
    if self % 2 == 0
      return nil
    else
      return true
    end
  end
  def even?
    if self % 2 == 0
      return true
    else
      return nil
    end
  end
end

Then just call it like this:

2.odd?
and you'll get nil
3.odd?
and you'll get true

The above is messy, I'm sure it can be cleaned up, but you get the idea.

···

On 10/25/06, Brad Tilley <rtilley@vt.edu> wrote:

What's the quickest way to determine if an int is an even number
2,4,6,8...
Anything such as int.even or int.odd returning true/false? I want to
test the length of an array and add one element to it if it has an odd
number of elements.

--
Robert W. Oliver II
President, OCS Solutions, Inc. - Web Hosting and Development

Toll-Free Phone - 1-800-672-8415

OCS Ruby Forums - http://www.rubyforums.com/
My Blog - http://www.rwoliver.com/

Integer#[n] returns a 1 or 0 corresponding to bit n, with n=0 being
the least significant bit.

so

Even:
    an_int[0].zero?

Odd:
    an_int[0].nonzero?

···

On 10/25/06, Brad Tilley <rtilley@vt.edu> wrote:

What's the quickest way to determine if an int is an even number
2,4,6,8...
Anything such as int.even or int.odd returning true/false? I want to
test the length of an array and add one element to it if it has an odd
number of elements.

Thank you!

--
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

Thanks for all the examples guys! Being Ruby, I thought there might be
some super simple method that just magically did this. I'll stick with
the old-fashioned modulo test.

···

--
Posted via http://www.ruby-forum.com/.

Argh! Ok, I keep coming across code like this, and it's driving me nuts. It's like writing:

   if true then true else false end

Well, duh! :slight_smile:

Just write this:

   class Fixnum
     def odd?
       self % 2 == 1
     end
     def even?
       self % 2 == 0
     end
   end

Pete Yandell

···

On 26/10/2006, at 9:25 AM, Robert Oliver wrote:

You can determine if a number is odd by doing this:

class Fixnum
def odd?
   if self % 2 == 0
     return nil
   else
     return true
   end
end
def even?
   if self % 2 == 0
     return true
   else
     return nil
   end
end
end

Brad Tilley wrote:

Thanks for all the examples guys! Being Ruby, I thought there might be
some super simple method that just magically did this. I'll stick with
the old-fashioned modulo test.

If speed matters, the modulo test is way slower than testing the LSB.

···

--
Paul Lutus
http://www.arachnoid.com

class Fixnum
  def even?
    (self % 2).zero?
  end
  def odd?
    !even?
  end
end

···

On 10/26/06, Pete Yandell <pete.yandell@gmail.com> wrote:

On 26/10/2006, at 9:25 AM, Robert Oliver wrote:

> You can determine if a number is odd by doing this:
>
> class Fixnum
> def odd?
> if self % 2 == 0
> return nil
> else
> return true
> end
> end
> def even?
> if self % 2 == 0
> return true
> else
> return nil
> end
> end
> end

Argh! Ok, I keep coming across code like this, and it's driving me
nuts. It's like writing:

   if true then true else false end

Well, duh! :slight_smile:

Just write this:

   class Fixnum
     def odd?
       self % 2 == 1
     end
     def even?
       self % 2 == 0
     end
   end

Paul Lutus wrote:

Brad Tilley wrote:

Thanks for all the examples guys! Being Ruby, I thought there might be
some super simple method that just magically did this. I'll stick with
the old-fashioned modulo test.

If speed matters, the modulo test is way slower than testing the LSB.

Do you mean on a specific architecture, or is there a Ruby-specific reason for one to be slower than the other?

I normally do that, but I remember somewhere reading that it was bad form to
not include the return statement. I'm not sure where this was. Is anyone
familiar with this syntax quasi-rule?

···

On 10/26/06, Wilson Bilkovich <wilsonb@gmail.com> wrote:

class Fixnum
  def even?
    (self % 2).zero?
  end
  def odd?
    !even?
  end
end

--
Robert W. Oliver II
President, OCS Solutions, Inc. - Web Hosting and Development

Toll-Free Phone - 1-800-672-8415

OCS Ruby Forums - http://www.rubyforums.com/
My Blog - http://www.rwoliver.com/

Not really ruby-specific, and for the most part architecture independent.

Modulo basically involves an integer division operation, whereas bit
testing is a simple logical and with a mask.

(int & 1).zero? is probably faster than
int[0].zero?

Since the latter generates the mask using the bit position.

and both should be faster than

(int % 2).zero?

But it it's performance critical, benchmarking is recommended to
verify. One should never simply take 'rules of thumb' for granted.

···

On 10/25/06, Jeffrey Schwab <jeff@schwabcenter.com> wrote:

Paul Lutus wrote:
> Brad Tilley wrote:
>
>> Thanks for all the examples guys! Being Ruby, I thought there might be
>> some super simple method that just magically did this. I'll stick with
>> the old-fashioned modulo test.
>
> If speed matters, the modulo test is way slower than testing the LSB.

Do you mean on a specific architecture, or is there a Ruby-specific
reason for one to be slower than the other?

--
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

Modulo uses division hardware, which is slower than the hardware for
bitwise operations. Most C compilers know how to optimize this sort of
thing when it's known in advance that you're doing mod 2. I doubt Ruby's
that smart.

--Ken

···

On Thu, 26 Oct 2006 01:19:08 +0000, Jeffrey Schwab wrote:

Paul Lutus wrote:

Brad Tilley wrote:

Thanks for all the examples guys! Being Ruby, I thought there might be
some super simple method that just magically did this. I'll stick with
the old-fashioned modulo test.

If speed matters, the modulo test is way slower than testing the LSB.

Do you mean on a specific architecture, or is there a Ruby-specific
reason for one to be slower than the other?

--
Ken Bloom. PhD candidate. Linguistic Cognition Laboratory.
Department of Computer Science. Illinois Institute of Technology.
http://www.iit.edu/~kbloom1/
I've added a signing subkey to my GPG key. Please update your keyring.

Robert Oliver wrote:

···

On 10/26/06, Wilson Bilkovich <wilsonb@gmail.com> wrote:

class Fixnum
  def even?
    (self % 2).zero?
  end
  def odd?
    !even?
  end
end

I normally do that, but I remember somewhere reading that it was bad
form to
not include the return statement. I'm not sure where this was. Is anyone
familiar with this syntax quasi-rule?

I tend to use un-necessary "return" statements in most of my code,
because it makes it easier for me to read. But I suppose the language
designers that provide simplified syntax do so for a reason, so I would
say the correct style is the minimum amount of code the language allows.

Robert Oliver wrote:

class Fixnum
  def even?
    (self % 2).zero?
  end
  def odd?
    !even?
  end
end

I normally do that, but I remember somewhere reading that it was
bad form to not include the return statement. I'm not sure where
this was. Is anyone familiar with this syntax quasi-rule?

It is a programming-paradigm-dependent semantics rule. If one follows
the functional paradigm, one would write leap? in this way:

class Fixnum
~ def leap?
~ if (self % 400).zero?
~ true
~ elsif (self % 100).zero?
~ false
~ elsif (self % 4).zero?
~ true
~ else
~ false
~ end
~ end
end

if one follows the proceural paradigm one would rather write

class Fixnum
~ def leap?
~ if (self % 400).zero?
~ return true
~ elsif (self % 100).zero?
~ return false
~ elsif (self % 4).zero?
~ return true
~ else
~ return false
~ end
~ end
end

Bad style came into play if one would write something like

class Fixnum
~ def leap?
~ if (self % 400).zero?
~ return true
~ elsif (self % 100).zero?
~ return false
~ elsif (self % 4).zero?
~ return true
~ end
~ false
~ end
end

because in this case one starts with the procedural paradigm and
switches to the functional paradigm. An example of bad style were:

class Fixnum
~ def leap?
~ return true if (self % 400).zero?
~ return false if (self % 100).zero?
~ return true if (self % 4).zero?
~ false
~ end
end

While not being necessary it improves code to add a return in order
to stick to the procedural paradigm.

class Fixnum
~ def leap?
~ return true if (self % 400).zero?
~ return false if (self % 100).zero?
~ return true if (self % 4).zero?
~ return false
~ end
end

Some rules of thumb:

~ - Use or avoid return consistently.

~ - Make your code reflect your intention to the maximum extend
~ permited by the language you use - if you want a procedure to
~ return some value use "return", if you want a function to evaluate
~ to some value don't.

HTH,

Jupp

···

On 10/26/06, Wilson Bilkovich <wilsonb@gmail.com> wrote:

An extremely quick "benchmark"

0.upto(1000000) do |i|
        (i & 1).zero?
end

0.upto(1000000) do |i|
        i[0].zero?
end

0.upto(1000000) do |i|
        (i % 2).zero?
end

I ran each of the above, and all of them averaged between, 500ms, and 550ms
of sys time. So I'd say that realistically there is no significant
performance difference in any of the methods.

···

On 10/25/06, Rick DeNatale <rick.denatale@gmail.com> wrote:

On 10/25/06, Jeffrey Schwab <jeff@schwabcenter.com> wrote:
> Paul Lutus wrote:
> > Brad Tilley wrote:
> >
> >> Thanks for all the examples guys! Being Ruby, I thought there might
be
> >> some super simple method that just magically did this. I'll stick
with
> >> the old-fashioned modulo test.
> >
> > If speed matters, the modulo test is way slower than testing the LSB.
>
> Do you mean on a specific architecture, or is there a Ruby-specific
> reason for one to be slower than the other?

Not really ruby-specific, and for the most part architecture independent.

Modulo basically involves an integer division operation, whereas bit
testing is a simple logical and with a mask.

(int & 1).zero? is probably faster than
int[0].zero?

Since the latter generates the mask using the bit position.

and both should be faster than

(int % 2).zero?

But it it's performance critical, benchmarking is recommended to
verify. One should never simply take 'rules of thumb' for granted.

--
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

--
===Tanner Burson===
tanner.burson@gmail.com
http://tannerburson.com <---Might even work one day...

Rick DeNatale wrote:

(int & 1).zero? is probably faster than
int[0].zero?

Since the latter generates the mask using the bit position.

and both should be faster than

(int % 2).zero?

But it it's performance critical, benchmarking is recommended to
verify. One should never simply take 'rules of thumb' for granted.

Let's just do it rather than speculating:

require 'benchmark'

ITERATIONS = 1_000_000
MAX_INT = 2 ** 30
NUMS = (1..ITERATIONS).map{ rand(MAX_INT) }
Benchmark.bmbm{ |x|
  x.report '(n % 2).zero?' do
    NUMS.each{ |n|
      (n % 2).zero?
    }
  end

  x.report 'n[0].zero?' do
    NUMS.each{ |n|
      n[0].zero?
    }
  end

  x.report '(n & 1).zero?' do
    NUMS.each{ |n|
      (n & 1).zero?
    }
  end
}

#=> Rehearsal -------------------------------------------------
#=> (n % 2).zero? 2.060000 0.020000 2.080000 ( 2.244595)
#=> n[0].zero? 1.960000 0.010000 1.970000 ( 2.145238)
#=> (n & 1).zero? 1.990000 0.020000 2.010000 ( 2.275232)
#=> ---------------------------------------- total: 6.060000sec
#=>
#=> user system total real
#=> (n % 2).zero? 2.070000 0.010000 2.080000 ( 2.315105)
#=> n[0].zero? 1.960000 0.020000 1.980000 ( 2.143038)
#=> (n & 1).zero? 1.990000 0.010000 2.000000 ( 2.173120)

There is a very, very, very small difference in speed.

Ken Bloom wrote:

···

On Thu, 26 Oct 2006 01:19:08 +0000, Jeffrey Schwab wrote:

Paul Lutus wrote:

Brad Tilley wrote:

Thanks for all the examples guys! Being Ruby, I thought there might be
some super simple method that just magically did this. I'll stick with
the old-fashioned modulo test.

If speed matters, the modulo test is way slower than testing the LSB.

Do you mean on a specific architecture, or is there a Ruby-specific reason for one to be slower than the other?

Modulo uses division hardware, which is slower than the hardware for
bitwise operations.

On what modern architecture? (I write x86 firmware.)

M. Edward (Ed) Borasky wrote:

Robert Oliver wrote:

class Fixnum
  def even?
    (self % 2).zero?
  end
  def odd?
    !even?
  end
end

I normally do that, but I remember somewhere reading that it was bad
form to
not include the return statement. I'm not sure where this was. Is anyone
familiar with this syntax quasi-rule?

I tend to use un-necessary "return" statements in most of my code,
because it makes it easier for me to read. But I suppose the language
designers that provide simplified syntax do so for a reason, so I would
say the correct style is the minimum amount of code the language allows.

Not including a "return" statement makes it all a bit more "functional" in my view. Basically, I'll leave off the return if the method is really simple and it's obvious what the last statement is and that it's being returned. If there's any complex control flow going on then it's nicer to give the "reader"(potentially just yourself, but being nice to your future self is good) the visual clue as to what's actually being returned, even if it's still the last statement executed.

···

On 10/26/06, Wilson Bilkovich <wilsonb@gmail.com> wrote:

Phrogz wrote:

Rick DeNatale wrote:

(int & 1).zero? is probably faster than
int[0].zero?

Since the latter generates the mask using the bit position.

and both should be faster than

(int % 2).zero?

But it it's performance critical, benchmarking is recommended to
verify. One should never simply take 'rules of thumb' for granted.

Let's just do it rather than speculating:

require 'benchmark'

ITERATIONS = 1_000_000
MAX_INT = 2 ** 30
NUMS = (1..ITERATIONS).map{ rand(MAX_INT) }
Benchmark.bmbm{ |x|
  x.report '(n % 2).zero?' do
    NUMS.each{ |n|
      (n % 2).zero?
    }
  end

  x.report 'n[0].zero?' do
    NUMS.each{ |n|
      n[0].zero?
    }
  end

  x.report '(n & 1).zero?' do
    NUMS.each{ |n|
      (n & 1).zero?
    }
  end
}

#=> Rehearsal -------------------------------------------------
#=> (n % 2).zero? 2.060000 0.020000 2.080000 ( 2.244595)
#=> n[0].zero? 1.960000 0.010000 1.970000 ( 2.145238)
#=> (n & 1).zero? 1.990000 0.020000 2.010000 ( 2.275232)
#=> ---------------------------------------- total: 6.060000sec
#=>
#=> user system total real
#=> (n % 2).zero? 2.070000 0.010000 2.080000 ( 2.315105)
#=> n[0].zero? 1.960000 0.020000 1.980000 ( 2.143038)
#=> (n & 1).zero? 1.990000 0.010000 2.000000 ( 2.173120)

There is a very, very, very small difference in speed.

I feel like Alice falling into the rabbit hole. I never thought I would see
the day when the difference between a division and a bit test would be
reduced to insignificance by other factors. Obviously I started thinking
about this (and developing my prejudices) before there were numeric
coprocessors.

Nice demonstration, BTW.

···

--
Paul Lutus
http://www.arachnoid.com