in reply to Re: porting C code to Perl (updated!)
in thread porting C code to Perl
your insights are exactly what I needed. I spotted the type casting of int but I have not thought it constrained all the operations too.. what a complicated world they have with C..
Now I ported to a more perlish versions, but speaking frankly, I'm quite struggling with it's efficiency. Infact the inner for loop for a precision of 1000 cause each of it's line to be called something like 3 million of times if I read correctly the Devel::NYTProf output.
UPDATE some output from NYTProf Performance Profile
Line Statements Time on line Code 9 1002 49.4ms for $i(reverse 1..$l){ 10 3347682 441ms $x=10*$a[$i-1]+$q*$i; 11 3347682 474ms $a[$i-1]=$x%(2*$i-1); 12 3347682 882ms $q=int($x/(2*$i-1))
This inner for loop if I read correctly it's not influenced by the outer $j and only set a final (?) $q and the array element $a[$i-1] so i'm trying to cut the loop from there and prebuild an array of q linkable with $j indexes and prefilling the @a accordingly. No big luck until now.
In reality I'm working blindly not having well understood what the code do. I'll try a reverse eng. based on print statements if i do not desist sooner. Another ugly think I've done is the last line where I merely susbtitute the leading 03 with 3, any attempt to do this within the loop failed.
Anyway thank you again!
use strict; use warnings; my $n=1002; my $len = 1 + int (10 * $n / 3); my $pi; my @a= (2) x $len; my $nines = 0; my $predigit = 0; foreach my $j(1..$n){ my $q = 0; foreach my $i( reverse 1..$len){ my $x = 10 * $a[$i-1] + $q * $i; $a[$i-1] = $x % (2 * $i - 1); $q = int($x / (2 * $i - 1)); } $a[0]=$q%10; $q=int($q/10); if (9 == $q){ ++$nines; } elsif(10 == $q){ $pi.=$predigit + 1; for (my $k = 0; $k < $nines; $k++){$pi.=0} $predigit = $nines = 0; } else{ $pi.= int $predigit; $predigit = $q; if(0 != $nines){ for (my $k = 0; $k < $nines; $k++) { $pi.=9; } $nines = 0; } } } print $pi=~s/^03/3./r;
PS and yes these are the Pi digits and the C source is what you spotted!
L*
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: porting C code to Perl -- solved
by haukex (Archbishop) on Oct 23, 2017 at 19:40 UTC | |
by Discipulus (Canon) on Oct 24, 2017 at 07:12 UTC | |
by haukex (Archbishop) on Oct 24, 2017 at 18:22 UTC | |
Re^3: porting C code to Perl -- solved
by marioroy (Prior) on Oct 24, 2017 at 04:30 UTC | |
Re^3: porting C code to Perl -- solved
by soonix (Chancellor) on Oct 23, 2017 at 18:41 UTC | |
by Discipulus (Canon) on Oct 23, 2017 at 19:59 UTC | |
Re^3: porting C code to Perl -- solved
by Monk::Thomas (Friar) on Oct 24, 2017 at 10:08 UTC |