Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Running for 10,000,000 twice I got 3.1405 the first run, and 3.1424 the second. (for an average of 3.1415) It's quite likely your rand() isn't perfect. (neither is mine 10,000,000 runs should give me a digit or two more accuracy).

Anyway, here is my favorite approximation for pi, mainly because it only uses the number 2. Even though two is normally a computer friendly number, this algorithm isn't, because it also uses sqrt's. With my perl, 14 iterations is gives the maximum accuracy: 3.14159265480759

#!/usr/bin/perl -w use strict; print "Enter how many iterations:\n"; chomp(my $i = <>); my $x = $i - 1; my $y = sqrt(2); do { $y = sqrt(2 + $y) while (--$x); $y = sqrt(2 - $y); } if $x; my $z = $y * (2 ** $i); print "Pi is close to: $z\n";

So, while not the best, but I have some strange affinity to it. :)

Ciao,
Gryn

p.s. Sorry for the cryptic code for a quick decrypt its: (2**n)*sqrt(2-sqrt(2+sqrt(2+sqrt(2+sqrt(2))))) with the number of 2's inside the sqrt equaling n.


In reply to Accuracy of Random Pi by gryng
in thread Pi calculator by Fingo

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 exploiting the Monastery: (3)
As of 2024-04-20 12:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found