Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Binomial Expansion

by crazyinsomniac (Prior)
on Mar 29, 2001 at 10:33 UTC ( [id://68056]=perlcraft: print w/replies, xml ) Need Help??

   1: #!perl -w
   2: 
   3: # BinomialExpansion.pl
   4: 
   5: # usage perl BinomialExpansion.pl n, where n is an integer > 0 
   6: 
   7: # ** the memory goes crazy after the 170th power
   8: # the expansion of (x+y)^170 peaks at 9.14484184513157e+049 * x^85 * y^85
   9: # so you can imagine what happens if you put int n>170
  10: 
  11: my $n = ($_=shift) > 0 ? int $_ :
  12:         die "'usage perl BinomialExpansion.pl 9, where n > 0'";
  13: 
  14: print _titled_hr(' Binomial Expansion For (x+y)^',$n,' ');
  15: 
  16: for my $j (0 .. $n)
  17: {
  18:     my $coefficient = nCr($n,$j);
  19:     my $nj=$n-$j;
  20:     print $coefficient;
  21:     print $_ = ($nj!=0)?( ($nj>1)?(' * x^'.$nj):(' * x') ):'';
  22:     print $_ = ($j!=0)?( ($j==1)?(' * y'):(' * y^'.$j) ):'';
  23:     print $_ = ($j!=$n)?(" +\n"):("\n");
  24: }
  25: 
  26: print ' 'x 25,' = (x + y)^',$n, "\n"x 3;
  27: 
  28: # returns n!/r!(n-r)!
  29: sub nCr
  30: {
  31:     my $n=shift;
  32:     my $r=shift;
  33: 
  34:     return int nFactorial($n) / int nFactorial($r) * int nFactorial($n-$r);
  35: }
  36: 
  37: # like the name says, n!
  38: sub nFactorial
  39: {
  40:     my $n=shift;
  41:     my $product = 1;
  42: 
  43:     while($n>0)
  44:     {
  45:         $product *= $n--;
  46:     }
  47: 
  48:     return  $product;
  49: }
  50: 
  51: # neat little titled hr, that does a < 80 chars since int rounds down
  52: # i really, really, like it
  53: sub _titled_hr
  54: {
  55:     my $string = join('', @_);
  56:     my $oy = int (80 -(length $string) )/ 2;
  57:     return "\n","-" x $oy, $string, "-" x $oy,"\n";
  58: }
  59: 
  60: __END__
  61: # some random things i say
  62: #1
  63: "--. .-. . . - --..   -.-- .----. .- .-.. .-.."
  64: 
  65: #2
  66: "...- .-. --- --- -- --..--   ...- .-. --- --- -- .----."
  67: 
  68: #3
  69: --- ..-.   .- .-.. .-..   - .... .   - .... .. -. --. ...   ..   .-.. --- ... -
  70: --..--
  71:   ..   -- .. ... ...   -- -.--   -- .. -. -..   - .... .   -- --- ... - .-.-.-
  72:     -....- -....-   --- --.. --.. .. .   --- ... -... --- ..- .-. -. .
  73: 
  74: # a lil sample from my machine
  75: 
  76: F:\>perl BinomialExpansion.pl 9
  77: 1 * x^9 +
  78: 9 * x^8 * y +
  79: 36 * x^7 * y^2 +
  80: 84 * x^6 * y^3 +
  81: 126 * x^5 * y^4 +
  82: 126 * x^4 * y^5 +
  83: 84 * x^3 * y^6 +
  84: 36 * x^2 * y^7 +
  85: 9 * x * y^8 +
  86: 1 *  * y^9
  87:                  = (x + y)^9
  88: F:\>
  89: 
  90: # Notice a pattern? Fleet attack!
  91: # >
  92: #   >
  93: #     >
  94: #     >
  95: #       >
  96: #       >
  97: #     >
  98: #     >
  99: #   >
 100: # >

Replies are listed 'Best First'.
Sierpinskij (Re: Binomial Expansion)
by larsen (Parson) on Mar 29, 2001 at 13:48 UTC
    A pattern? Yes, of course!
    Here what you can obtain if you paint a Pascal Triangle.

    Update I think this link could be amusing: Pascal's Triangle

    #!/usr/bin/perl use strict; my $n = 10; for my $i (0 .. $n) { for my $j (0 .. $i) { my $coefficient = nCr($i, $j); if ($coefficient % 2) { print '#'; } else { print ' '; } } print "\n"; } # returns n!/r!(n-r)! sub nCr { my $n=shift; my $r=shift; return int nFactorial($n) / int nFactorial($r) * int nFactorial($n +-$r); } # like the name says, n! sub nFactorial { my $n=shift; my $product = 1; while($n>0) { $product *= $n--; } return $product; }

      I thought part of the point of Pascal's triangle was to show that you don't have to compute factorials:

      my @line= (1); while( 1 ) { print "@line\n"; push @line, 0; for( reverse 1..$#line ) { $line[$_] += $line[$_-1]; } }
      Be sure to pipe the output to more.

              - tye (but my friends call me "Tye")
      Not only is it Pacal's triangle, it's also a Sirpinski Gasket if you associate one character/color to even numbers, and another to odd.

      Math rox.

      Update: Ugh i am not awake yet. Forgive my redundancy.

      i found that code some times ago, unfortunately i don't know the author. i post here, maybe someone don't know.
      #!/usr/bin/perl -l s--@{[(gE^Ge)=~/[^g^e]/g]}[g^e]x((!!+~~g^e^g^e)<<pop).!gE-ge, s-[^ge^ge]-s,,,,s,@{[(g^';').(e^'?')]},(G^'/').(E^'|')^Ge,ge, print,s,(?<=/[^g^e])[^g^e][^g^e],$&^(G^'/').(E^'|')^gE,ge-ge
Re: Binomial Expansion
by ariels (Curate) on Mar 29, 2001 at 14:41 UTC
    The nCr function above is horribly inaccurate. While n!/r!(n-r)! is indeed a valid formula for binomial coefficients, it's hardly a good way to calculate them. Here's a better way:
    sub nCr { my ($n, $r) = @_; my $res = 1; for my $i (1..$r) { $res *= $n--; $res /= $i; } $res; }
    Why $res remains an integer (for "reasonable" parameter values) remains an exercise for the reader...
      Ok, for fun, and because I like mathematical proofs (I made it to the USA Mathematic Olympiad twice), here's the proof I use. In pseudo-code, the n-choose-r function looks like:
      nCr (n,r) { res = 1; for i in 1 .. r { res *= n; n--; res /= i; } return res; }
      The question is, why does res remain an integer? It is not difficult to show that res /= 1 is an integer, but how can we prove that by the time we get to res /= 7, res is a multiple of 7?

      The proof is that by the time we have gotten to res /= X, we have multiplied res's original value, 1, by X continuous integer, and in every series of X continuous integers, there will be one number divisible by X:

      X = 2, series = (y, y+1); one is div. by 2 X = 3, series = (y, y+1, y+2); one is div. by 3 ... in nCr(17,7), n is of the series (17,16,15,14,13,12,11) i is of the series ( 1, 2, 3, 4, 5, 6, 7) (17/1) (17/1) (16/2) (17/1) (16/2) (15/3) (17/1) (16/4) (15/3) (14/2) (17/1) (16/4) (15/(3*5)) (14/2) (13/1) (17/1) (16/4) (15/(3*5)) (14/2) (13/1) (12/6) (17/1) (16/4) (15/(3*5)) (14/(2*7)) (13/1) (12/6) (11/1)
      We're allowed to move the denominators around like I did, because we've already showed the product will already be an integer. The product looks like:
      r ----- | | n - (i-1) | | --------- | | i i=1


      japhy -- Perl and Regex Hacker
      I take great offense in calling my nCr function horribly inaccurate.

      You do say right away that is a valid formula for binomial coefficients, but then you say it's hardly a good one?

      It is a formula for calculating r-combinations, not binomial coefficients.

      The formula for binomial expansion is:

                n
                _
      (x+y)^n = \ C(n,j) * x^(n-j) *y^j
                /
                ¯
                j=0
      

      And btw, it is the definitive formula for calculating r-combinations. It's like saying 4/2 is not the same as 2. While 2 is a better way to write 4/2, not every one recognizes 2 right away, and I feel, for the benefit of the reader of me 'craft', n!/(r!(n-r)! is a better way to go.

      As for your function, it is shorter, but a litle mysterious when it comes to the math.

      
                     9!         9*8*7* 6!      9*8*7   504
       nCr(9,3) = ---------   = ----------- = ------ = --- = 84
                  3!*(9-3)!     3*2*1*(6!)     3*2*1    6
      
       which follows from the fact that nCr(n,r) = nCr(n,n-r)
      
       n!              n!               n!         _    n!
      ------- = ----------------- = -------------  = ---------
      r!(n-r)    (n-r)!(n-(n-r))!   (n-r)!(n-n+r)!   (n-r)!(r)!
      
      This however only works for n>r, as long as n and r are both non-negative integers, but shouldn't be a problem in this case.

      As for things being integer, since the input is an integer, it follows that any integer multiple of that integer, will also be an integer.

      update:
      I give, I give, theory v. practice, there is a difference.

       
      ___crazyinsomniac_______________________________________
      Disclaimer: Don't blame. It came from inside the void

      perl -e "$q=$_;map({chr unpack qq;H*;,$_}split(q;;,q*H*));print;$q/$q;"

        Those formulas are all the same in mathematical terms. But we are talking floating point arithmatic here. Computing the factorials and then dividing is going to introduce errors into the computation for fairly small values of n here.

                - tye (but my friends call me "Tye")
        If you want to understand the math, I fully agree with your use of the formula. Furthermore for more complex combinatorial problems, understand how to get those formulas is extremely important.

        That said, tye is right as well. While in theory that calculation gets the right answer, in practice it starts to be inaccurate for fairly small numbers. You can get around this by using a big integer package. (Or a language that understands integers of arbitrary size.) But that will be somewhat slow.

        If you want to understand this, go with the formula. If you want to calculate it, go with the tricks. If you want to calculate answers to arbitrary problems, be prepared to manipulate big integers and hope that performance doesn't matter.

        And if you want an even better example some day, bug me about why you should always use row-reduction to find the inverses of matrices rather than Cramer's formula. (Hint: Think numerically unstable and exponential running time, vs n**3 and much better behaved.)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2024-03-19 09:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found