Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Numerical methods are deceptively difficult. They require exquisite attention to detail to make them work properly. For example, if you are getting dsin(30)=0.49999999999999945 then you have a serious bug.

For most hardware out there, you cannot properly initialize a variable such as pi by entering lots of digits in your program. This is because the internal precision of the machine exceeds the precision that you are normally allowed to print or initialize. So if you catch yourself typing in lots of digits of pi, you are doing something wrong. Here is a better way to do it:

use Math::Trig; my $pi= 4*atan2(1,1); my $deg_to_radian= $pi/180; print sin(30*$deg_to_radian),"\n";
This prints 0.5, as you would hope that it would.

As far as the snippet goes, it is seriously borked. Among other problems, it has problems with the implicit string/numeric conversion that perl uses. This causes it to give different results for

approx(".00000000001")
and
approx(".00000000001"+0)

The recent CPAN module Math::SnapTo version 0.02 also has serious errors. For good rounding, use Math::Round. It doesn't do exactly what you want (that is, round like a human), but neither does this snippet or Math::SnapTo.

It should work perfectly the first time! - toma


In reply to Re: Fix floats like you do in your head by toma
in thread Fix floats like you do in your head by tachyon

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2024-04-24 09:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found