Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Problems with number resolution

by syphilis (Archbishop)
on Jan 01, 2018 at 23:19 UTC ( [id://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";
to
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.

Cheers,
Rob

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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-03-30 05:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found