Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Floating point problems

by bluescreen (Friar)
on Oct 24, 2010 at 15:54 UTC ( [id://867051] : note . print w/replies, xml ) Need Help??


in reply to Floating point problems

I really appreciate everybody's opinion here, really do. I've try other languages and they all have the same behaviour:

Smalltalk:
(0.6 / 0.2) asInteger 2
Python:
python -c 'print int(0.6/0.2)' 2
Ruby:
ruby -e 'print (0.6/0.2).to_i' 2

In the end I believe Dynamic languages ( perl, ruby, python ) should handle cases like this in a more elegant and seamless way.

Dynamic languages do a pretty job hiding the internal representation of numbers for the user, in the sense that you can create program without knowing whether a variable holds an integer, double, float, fixed precision or any other representation. We leave the details of picking the right representation to the compiler/interpreter, so we (users) could expect to handle such border cases also seamlessly.

As a final though,

  • do you think that everybody would easily spot why int(0.6/0.2) returns 2 instead of 3 ?
  • If print 3.0 returned 2.99999999 would you tell users that interpreter is doing the right job and users should stay away of using number with decimal places?

Replies are listed 'Best First'.
Re^2: Floating point problems
by lidden (Curate) on Oct 24, 2010 at 16:13 UTC
    But int is defined as truncating towards zero, if you do not want that behaviour use sprintf.

    If you could make int magical and sometimes behave differently. How would you avoid false positives?