From: Robert Klemme Date: 2009-12-22T23:46:54+09:00 Subject: Re: integers and floats 2009/12/22 Paul Smith : > On Tue, Dec 22, 2009 at 1:36 PM, Rajinder Yadav wrote: >> Paul Smith wrote: >>> >>> On Tue, Dec 22, 2009 at 1:01 PM, Rajinder Yadav >>> wrote: >>>> >>>> Can someone explain to me why Ruby treats integers and floating point >>>> numbers differently? >>>> >>>> irb(main):069:0> 12.equal? 12 >>>> => true >>>> >>>> irb(main):071:0> 12.0.equal? 12.0 >>>> => false >>> >>> Because they're different :) >> >> thanks, I understand the object_id >> >> my question is why is 12.0 constructed each time and 12 is immediate? does >> it have to do with the fact that floats are simply binary approximation. > > I'm not sure how you would make floating point numbers immediate. Well, you could - but at the expense of dramatically increased memory need for every Ruby program because a standard float needs more bytes to store than an int and so every object reference would have to be significantly larger. http://en.wikipedia.org/wiki/Tagged_pointer Plase see also the other current thread "Ruby's implementation of Fixnum-assignment". > Fixnums can be immediate by a clever trick with the object_id.  This > is done presumably for performance - application deal with small > integers all the time. It's rather the other way round: making Fixnums immediate is the clever trick and Fixnum's object_id is a derivative of that trick. > Is anything else an immediate object in this sense? AFAIK nil, true, false. > Symbols aren't immediate, but they have been made (presumbaly through > some kind of symbol table lookup) such that every :abc is the same > symbol. > > I don't think anything else works this way either, symbols have a > particular use case that is different to strings, and Ruby can play > with both. > > Could you make floats work the same way as symbols?  Probably.  Is it > worth it?  Under what use case is it important that all 12.0s be the > exact same object? I don't think it's worthwhile because at any point in time there are not many float instances with the same value other than in artificial test cases. The price to pay (memory, see above) is just too high. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/