Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Anonymous Subroutine

by AnomalousMonk (Bishop)
on Nov 27, 2017 at 02:59 UTC ( #1204305=note: print w/replies, xml ) Need Help??


in reply to Anonymous Subroutine

... calculate the sum of 1^2 + 2^2 + 3^2 + …. + n^2,(these are exponents) ...
 $sum = 1**2+2**2+3**2+4**2+5**2+6**2+7**+$n**2;
... my calculation is wrong the results is not what it should be, why?

You've left out the …. part of the summation specification from the
    $sum = 1**2+2**2+3**2+4**2+5**2+6**2+7**+$n**2;
statement (update: which is in error in any event: what is the  7**+$n**2 term supposed to represent?). If n were 15, where are 8, 9, 10, 11, 12, 13, 14 in the sequence of numbers to be squared and summed?

c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(dd); use List::Util qw(sum reduce); ;; my $n = 15; dd 1 .. $n; dd map $_**2, 1 .. $n; dd sum map $_**2, 1 .. $n; ;; use vars qw($a $b); dd reduce { $a + $b**2 } 1 .. $n; " (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) (1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225) 1240 1240
I haven't tested it, but NetWallah's solution looks right.

Update: See Range Operators in perlop for the  .. operator in list context.

Update 2: I actually missed the whole

for ('$i=0; <= $n; $i++') { $sum += $i; }
piece of the OPed code, but that's ok because without strictures and warnings enabled, it's just a no-op in the final execution. :)

Update 3: Changed example code to use ranges of  1 .. $n with  $n initialized to 15 instead of literal  1 .. 15 ranges; makes the point a little better. Also added the reduce example.


Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2020-01-21 23:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?