[sup-talk] Util - Fixnum num_digits is wrong

Shot (Piotr Szotkowski) shot at hot.pl
Mon Dec 3 05:52:10 EST 2007


Ian Taylor:

>  class Fixnum
>    def num_digits base=10
>      return 1 if self == 0
> -    1 + (Math.log(self) / Math.log(10)).floor
> +    1 + (Math.log(self) / Math.log(base)).floor
>    end

Math.log and Float#/ returning Floats means the above
approach is prone to the IEEE 754 representation inaccuracy.

Wouldn’t the below make more sense?

class Fixnum
  def num_digits base = 10
    to_s(base).size
  end
end

-- Shot
-- 
> Who wants to recommend a Usenet reader for little ol' me?
I recommend Garrett Morris, particularly if you're hard-of-hearing.
      -- jennifer friedoff and Joseph Nebus, rec.arts.tv.mst3k.misc
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 191 bytes
Desc: not available
Url : http://rubyforge.org/pipermail/sup-talk/attachments/20071203/37b62dab/attachment.bin 


More information about the sup-talk mailing list