Beefy Boxes and Bandwidth Generously Provided by pair Networks DiBona
Perl-Sensitive Sunglasses
 
PerlMonks  

(tye)Re3: In theory, theory and practice are the same...

by tye (Cardinal)
on Apr 01, 2001 at 08:09 UTC ( #68782=note: print w/ replies, xml ) Need Help??


in reply to Re (tilly) 1: In theory, theory and practice are the same...
in thread Binomial Expansion

I stand by my (quite conservative) statement. It does introduce errors for fairly small values of n. It is also at least twice as slow (it can be orders of magnitude slower).

But the greatest weakness to my mind is the following output:

200 choose 1: 200 vs. -1.#IND (1.#QNAN). Rate easy nice easy 1464/s -- -96% nice 34687/s 2270% --
Now that is quite a large error term, don't you think?

Yes, there is a useful space over which its accuracy is quite good (though not always as good), and thanks for exploring that.

Here is the code I used:

#!/usr/bin/perl -w use strict; use Benchmark qw( cmpthese ); sub fact { my $fact = 1; $fact *= $_ for 1..$_[0]; return $fact; } sub nice { my ($n, $r) = @_; my $res = 1; for my $i (1..$r) { $res *= $n--; $res /= $i; } return $res; } while( <> ) { my( $n, $m )= split ' '; my $nice= nice($n,$m); my $easy= fact($n)/fact($m)/fact($n-$m); print "$n choose $m: $nice vs. $easy (",abs($nice-$easy),").\n"; cmpthese( -3, { nice=>sub{nice($n,$m)}, easy=>sub{fact($n)/fact($m)/fact($n-$m)}, } ); }
        - tye (but my friends call me "Tye")


Comment on (tye)Re3: In theory, theory and practice are the same...
Select or Download Code
Re (tilly) 3: In theory, theory and practice are the same...
by tilly (Archbishop) on Apr 01, 2001 at 18:56 UTC
    It is a valid performance note. True But it isn't producing (visibly) wrong answers to take the naive approach.

    And the improvement is subtle. For instance consider the following slightly different version of your code:

    sub not_so_nice { my ($n, $r) = @_; my $res = 1; for my $i (1..$r) { $res *= ($n-- / $i); } return $res; }
    Someone was trying to simplify. But oops. In Perl you have just slowed down instead. In other languages you are going to get wrong answers. It takes a fair amount of knowledge to understand what changed. In fact it takes a fair amount of knowledge to understand why the original formula can be sped up by using your alternate approach.

    Now I appreciate that you have both pieces of knowledge. In fact the necessary analysis is probably almost a reflex for you, just like it is for me. But not everyone has the math background that we do...

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2014-04-19 21:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (483 votes), past polls