NYCJUG/Projects/Pascal

From J Wiki
Jump to navigation Jump to search

Interesting relation between Pascal's triangle and Sierpinksi triangles also demonstrating an effect of limited numeric precision and how to adjust for it.

A Graphic Representation of Pascal's Triangle

Celebrity Death-Match: Pascal vs. Sierpinksi
Session Image
   Pascal =: i. !/ i.

   Pascal 5
1 1 1 1 1
0 1 2 3 4
0 0 1 3 6
0 0 0 1 4
0 0 0 0 1
   load 'viewmat'
   $pt50=. Pascal 50
50 50
   viewmat 5|pt50
   load 'logo'
   saveBMPFl 'C:\amisc\j\nycjug\Pascal50mod5.bmp'

Pascal1.png
   viewmat 11|pt50

   saveBMPFl 'C:\amisc\j\nycjug\Pascal50mod11.bmp'

Pascal2.png
   viewmat 3|pt50

   saveBMPFl 'C:\amisc\j\nycjug\Pascal50mod3.bmp'
   NB. Why does it look "broken" on the right?
   >./,pt50
6.3205303e13
   /:~,pt50
0 0 0 0 0 0...
   \:~,pt50
6.3205303e13 6.3205303e13 5.8343357e13...
   3|10{.\:~,pt50
0 0 0 0 0 0 0 0 0 0 NB. Aha! Looks suspicious...
   NB. We ran out of precision on the large values...

Pascal3.png
   $pt50=. Pascal 50x NB. Use extended precision argument

50 50

   \:~,pt50 NB. Now large numbers to full precision
63205303218876 63205303218876...
   3|10{.\:~,pt50 NB. So no spurious zeros on right edge
0 0 0 0 1 1 1 1 0 0
   viewmat 3|pt50

Pascal4.png

Another Way to Show Pascal's Triangle

First, define a verb to show a row of the triangle without trailing zeros:

   showRownz=: 13 : 'smoutput y{.~y i. 0'

Then, define a simple version of Pascal to be applied recursively:

   pascal1=: 13 : '({.y),(2+/\y),{:y'

Now, combine them:

   showRownz"1 pascal1^:(i.10)],1
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1