DEV Community

Discussion on: Programs to Compute Trig Functions in Python, JavaScript, & Perl (with Maclaurin Series)

Collapse
 
matthewpersico profile image
Matthew O. Persico

One thing you should play with is 'memoization' and recursion. For those not familiar with the term, it is the caching of function results using the arguments as a key. In Perl, it's as simple as using the Memoize module. Not sure about the other languages' implementations.

Now, when calculating the factorial in a loop, memoization may not save you much. But in a recursive implementation, memoization is a tremendous win.

Something for you to have in your back pocket.

As for your Perl, it is very good - clear and very concise. One improvement for space and copy time considerations:

my @nums_to_multiply = (1..$x);
for(@nums_to_multiply){
    $n *= $_;
}
Enter fullscreen mode Exit fullscreen mode

can be replaced with

for(1..$x) {
    $n *= $_;
}
Enter fullscreen mode Exit fullscreen mode

That will save you the memory and the time to copy that series into the array.

A second suggestion:

$i = $i_start;
while($i < $i_start + $ITERATIONS) {
Enter fullscreen mode Exit fullscreen mode

can be replaced with

use strict; # At the top of the code
...
my $i = $i_start;
my $i_end = $i_start + $ITERATIONS
while($i < $i_end) {
Enter fullscreen mode Exit fullscreen mode

No need in recalculating the same number over and over in the loop.

Excellent article.

Collapse
 
matthewpersico profile image
Matthew O. Persico

Also, by adding use strict; at the top of your Perl code, you will get some errors about undefined vars. Just add mys in the appropriate places and you'll be fine. Always include use strict; in addition to use warnings;. It will catch unintended overlapping global usage of variables, which is a bear to debug, especially as the code gets longer. Again, excellent article.