Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Getting stranger values in subtraction

by Laurent_R (Canon)
on Feb 06, 2016 at 10:44 UTC ( [id://1154560]=note: print w/replies, xml ) Need Help??


in reply to Getting stranger values in subtraction

Just as a teaser, running choroba's sum under Perl 5:
DB<1> $x = 319.02 - 112.09 - 69.75 - 113.57 - 23.61; DB<2> p $x -1.4210854715202e-14
In both Python and Ruby, the result is -1.4210854715202004e-14, which might seem more accurate (3 more digits), but happens to be in fact a very little bit further from truth.

The same in Perl 6:

> my $x = 319.02 - 112.09 - 69.75 - 113.57 - 23.61; 0 > say sprintf "%.50f", $x 0.00000000000000000000000000000000000000000000000000 > say $x == 0; True
Not only does Perl 6 give the correct result, even when printing 50 decimal digits, but even comparing the result with 0 gives the correct answer.

Replies are listed 'Best First'.
Re^2: Getting stranger values in subtraction
by BillKSmith (Monsignor) on Feb 06, 2016 at 14:52 UTC
    Please explain why language makes a difference. All the references given so far suggest that it should not.
    Bill
      Hi Bill,

      Perl 6 is converting fractional numbers not into floating-point numbers as most languages, but into Rat (rational) type values. Internally, rational type numbers are in fact made of pairs of integer numbers, one for the numerator and one for the denominator, stored separately. So the numeric literal 319.02 is stored internally as something like (numerator = 31902, denominator = 100). When making arithmetic operations on such numbers, Perl 6 will happily add (or subtract) the integers and then print the result as a rational number. The result is accurate because there is no use of floating-point number approximation.

      Consider the following code introspecting the types of values and variables:

      > say 42.WHAT; (Int) > say 319.02.WHAT; (Rat) > say $x.WHAT; (Rat)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1154560]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2024-03-28 10:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found