Richard Cole
4/29/2005 4:36:00 AM
Brian Schröder wrote:
>On 29/04/05, Richard Cole <rcole@itee.uq.edu.au> wrote:
>
>
>>I've got a ruby program that's running quite slowly. I ran the profiler
>>to try to find out what's causing the hold up (see the profile output
>>below) and it looks like Integer#gcd is a culprit. My code is basically
>>a canvas with a bunch of canvas items and so it does some integer
>>computation, but somehow integers are getting converted into rationals
>>and then being simplified which appears to be taking up heaps of time.
>>
>>Has anyone got any hints on how to keep rationals out of my program? I
>>want to stick to integers and floats.
>>
>>regards,
>>
>>Richard.
>>[snip profiler output]
>>
>>
>
>well, just remove the line
>require 'rational'
>from your program.
>
>
I wasn't including 'rational'.
I have since discovered that rationals come from the 'mathn' library and
that library is being included by one of the libraries that I'm using. I
also found that x.div(y) produces an integer while x/y produces a
rational, so the answer is to use x.div(y) instead of x/y.
It is kind of freaky to have definition of x/y change dependent on
whether or not a library is included. One library changing the semantics
of the operations defined in another library is side effects on steroids.
irb(main):001:0> 1.div(2)
=> 0
irb(main):002:0> 1/2
=> 0
irb(main):003:0> require 'mathn'
=> true
irb(main):004:0> 1/2
=> 1/2
irb(main):005:0> 1.div(2)
=> 0
So there are three safe combinations (mathn,/), (mathn,div) (none,div)
and one unsafe combination (none,/). It is a pitty that the unsafe
combination is the first one that a nieve programmer would go for. Maybe
this can be cleaned up in the Ruby 2.0?
regards,
Richard.