How does ruby handle zero division? -


i trying find out how ruby handles 0 division. ruby returns different results based on class. tried

0/0     # => zerodivisionerror: divided 0     1/0     # => zerodivisionerror: divided 0 1.0/0   # => infinity 0.0/0.0 # => nan 

what happening here? shouldn't zerodivisionerror above cases?

update "infinity" standard data type, then?

(1.0/0).class  # => float 

ruby tracks ieee 754 floating point standard. wikipedia page not bad @ explaining seeing. many modern languages take same approach.

intuitively, behavior see makes perfect sense. in general,

1/<small number> = <big number> 

therefore in limit,

1/0 -> infinity    ,    -1/0 -> -infinity 

infinity constant understood floating point subsystem. on other hand

0 / <any non-zero> = 0 

so have conflict on 0/0. should 0 or infinity? ieee standard answer "not number", nan seeing, floating point constant.

the constants nan , plus or minus infinity propagate through expressions in way makes sense. example:

infinity + <any (necessarly finite) number> = infinity 

and

<any number> + nan = nan 

and more interestingly:

1 / infinity = 0 

which can try yourself:

irb(main):005:0> 1.0 / (1.0 / 0.0) => 0.0 

in manner floating point calculation can continue when has overflowed or divided 0 , still produce reasonably informative answer (though after know standard well, you'll see relying on answer bad idea).

this far behavior standard provides. others can selected. ruby you. source file numeric.c, function init_numeric, sets host processor division 0 propagates infinities. other languages might make other choices, example generate exception.


Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

jquery - How would i go about shortening this code? And to cancel the previous click on click of new section? -