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

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Indeed an interesting and clean approach!! As minor remark for a side note, when doing numerical integration one may likely be concerned about speed - not that relevant after all: I know full well that "premature optimization is the root of all evil", and if one is really concerned then he'd probably not doing this in Perl at all...

But all those dereferentiations and method accesses do not make for *speed* and apart a clean syntax I'm not really sure about what this gives you more than a C-style for loop which for once seems appropriate! (Most often in my experience it is not.)

Whatever, I stress once again that especially for educational purposes I find it great. In this sense, just for fun here's my rewrite of your code according to my own stylistic preferences. It should be just the same as yours modulo one tiny change in logic ("adaptive delta")

.
#!/usr/bin/perl use strict; use warnings; package Range; sub new { my ($class, $lower, $upper, $delta) = @_; bless { lower => $lower, upper => $upper, delta => $delta || ($upper-$lower)/1000, current => $lower, }, $class; } sub next { my $self = shift; ($self->{current} += $self->{delta}) < $self->{upper}; } package main; sub integrate { my ($function, $iter) = @_; my $sum; $sum += $function->($iter->{current}) * $iter->{delta} while $iter +->next; $sum; } printf "%.2f\n", integrate sub {(shift)**2}, new Range (2, 5); __END__

In reply to Re: Numerical integration by blazar
in thread Numerical integration by neniro

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 taking refuge in the Monastery: (7)
As of 2024-04-24 17:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found