Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: Problems with number resolution

by syphilis (Chancellor)
on Jan 01, 2018 at 23:19 UTC ( #1206522=note: print w/replies, xml ) Need Help??

in reply to Problems with number resolution

What can I do to prevent this kind of rounding error ?

Update: This is for the main part a rehash of what haukex had posted 5 hours earlier ... something I had failed to observe first time round.

You could change the last line of your code from:

print "$_ => $x\n";
printf "$_ => %.2f\n", $x;

Any module that does decimal (as opposed to binary) arithmetic would also provide correct results.
These modules include Math::BigFloat, Math::Decimal and Math::Decimal64.


Replies are listed 'Best First'.
Re^2: Problems with number resolution
by Anonymous Monk on Jan 03, 2018 at 14:20 UTC

    Thanks syphilis for your comment !

    I have looked into all suggestions and learned a lot ! Thanks to all !

    One question to Math::BigFloat, Math::Decimal and Math::Decimal64 :

    * Is this correct: As soon as at least one variable in an expression is a Math object (e.g. MEtoD64 after use Math::Decimal64 qw/:all/;) the calculation is done with the Math-functions, not with the standard functions. If there is no Math object in the expression, the calculation is still done with the fast standard functions. So I can use both (accurate and fast arithmetic) on the contrary when I use "use bignum", where I always use the accurate Math functions for all operations.

    * How can I check if a variable is a standard scalar or a Math object (like "ref" for hash/array)?

    * Is there a good overview document, pointing out the differences between Math::BigFloat, Math::Decimal, Math::Decimal64, Math::BigInt and Math::BigRat. (When to use which library best?)

      As to checking what kind of data is stored in a reference, use the ref function.

      Cheers, Sören

      Créateur des bugs mobiles - let loose once, run everywhere.
      (hooked on the Perl Programming language)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1206522]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2018-06-23 05:18 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (125 votes). Check out past polls.