Math & ScienceHelp: Creating Pascal-esque triangle (different structure and numbers) with TikZ for academic paper

Information and discussion about LaTeX's math and science related features (e.g. formulas, graphs).
Post Reply
spe420
Posts: 6
Joined: Tue Jun 03, 2025 8:52 am

Help: Creating Pascal-esque triangle (different structure and numbers) with TikZ for academic paper

Post by spe420 »

I am new to using TikZ, but have been using LaTeX via LyX for several years now. While I am not the most adept user, I am somewhat confident in my understanding of how the program works, albeit unfamiliar with all of its features. I understand this is a fairly high level task to try to implement, but I have very concerted reasons why this is my immediate aim.

I do not think the details of my project are entirely relevant or necessary to explain, however, I will say this:
–I am writing an academic paper that I hope to be able to submit to arxiv.org in the area of Number Theory;
–I have the vast majority of the paper written, with the exception of this particular diagram and an addendum to the end;
–I have recently purchased the LaTeX Cookbook, as well as LaTeX Graphics with TikZ, and have numerous other resources;
–I am willing to take the time necessary to under to learn the concepts, but have only limited coding experience (and via GUI in, LabVIEW).
Any assistance would be greatly appreciated.

The basic problems I need help with are:
1) some practical advice about most sensible workflow (I have read about so-called ERTs, and using text editors, etc. to insert "child documents" in LyX, exporting from CAS programs (I have installed Maxima, but yet to really learn how the program works);
2) how to make customizations to the generation of Pascal's Triangle-like structures (I have watched this tutorial:
https://www.youtube.com/watch?v=V1XBdHdofuw) such that, for example, I can stipulate the diagonal "column" containing the terms which would otherwise be the binomial coefficients k=0 (the left-most infinite series of ones), as being numbers generated according to a particular formula of my choosing, each successive diagonal row extending from the terms in the right-sided row of the triangle (i.e. the infinite series from n=1, k=1 down and to the left, and so on), being self-similar in their ratio to those terms contained in the first, with each term in the right-sided row (i.e. from n=0, k=0 down diagonally to the right) being the powers of any given input x, such that x^0=(n=0, k=0), *EDIT* x^1=(n=1, k=1), x^2=(n=2, k=2), etc. *EDIT*. I hope I have explained this adequately.

I understand this may be a very difficult problem... I have already begun, with some chagrin, to appreciate how difficult it is going to be to use this as a pretext for learning TikZ, and more of the fundamentals of LaTeX, but it is, I think, the only way to finish my paper as I have envisioned it. Any help that would be so graciously offered would be invaluable.

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

Stefan Kottwitz
Site Admin
Posts: 10343
Joined: Mon Mar 10, 2008 9:44 pm

Re: Help: Creating Pascal-esque triangle (different structure and numbers) with TikZ for academic paper

Post by Stefan Kottwitz »

Hi,

welcome to the forum!

I'm glad you got these books. I wrote them, and I'm happy when I hear that people read the books. I hope you liked them! Would you please be so kind to post a review for each on Amazon? (even if you got them in another bookstore). Reviews help me find readers and convince my publisher to allow me to produce another, extended edition. I want to create an extended edition of the TikZ book, so reviews would be greatly appreciated. For now, I made a Japanese translation (see TikZ.jp) and I'm working on a Japanese translation of the LaTeX Cookbook.

Regarding the workflow, I think that when you get more experience with LaTeX, you may switch from LyX to a LaTeX editor, such as TeXstudio or TeXworks. With a good template, you may not need LyX anymore. Compiling is fast nowadays, allowing you to track progress in a LaTeX editor that displays Code and PDF side by side. When I create TikZ pictures, I often compile them every few seconds to see the changes as I adjust. But LyX is good with ERT for now, of course.

I saw the Pascal triangle video. It's a short piece of not much explained code, but basically it is
  • a \foreach loop for the rows
  • a \foreach loop for the columns
  • a calculation for the coordinates of the nodes from row n and column k
  • a pgfmath calculation for the value in the node text
You can make it similar. If you like, share your code here and I can help improve it.

As your focus is on the paper as a result, and not on a TikZ code, you could also simply use tabular or array and put the calculated values in, using Excel for example. Ultimately, it's the PDF that's important, not the smart code, especially if there's a time pressure.

Stefan
LaTeX.org admin
spe420
Posts: 6
Joined: Tue Jun 03, 2025 8:52 am

Re: Help: Creating Pascal-esque triangle (different structure and numbers) with TikZ for academic paper

Post by spe420 »

Thanks for the advice. Apologies for taking my time in responding. Been busy, etc. I took your advice, and have gone with a LaTeX editor, specifically Texifier. Works very well. I have looked around on the internet, and gotten several examples of code that people have used to generate Pascal's Triangle, and begun to mess around with my own variation of it. Here is the rough draft:

Code: Select all

\documentclass[preview,border=12pt]{standalone}
\usepackage{array}

\begin{document}
Let $A$ be a set of $k$ elements and $B\subseteq A$ has $i$ elements.
\begin{center}
\begin{tabular}{>{$}l<{$}|*{7}{c}}
\multicolumn{1}{l}{$k$} &&&&&&&\\\cline{1-1} 
0 &$x_i^0$&&&&&&\\
1 &$\Sigma$&$x_i^1$&&&&&\\
2 &$\Sigma$&$\Sigma$&$x_i^2$&&&&\\
3 &$\Sigma$&$\Sigma$&$\Sigma$&$x_i^3$&&&\\
4 &$\Sigma$&$\Sigma$&$\Sigma$&$\Sigma$&$x_i^4$&&\\
5 &$\Sigma$&$\Sigma$&$\Sigma$&$\Sigma$&$\Sigma$&$x_i^5$&\\
6 &$\Sigma$&$\Sigma$&$\Sigma$&$\Sigma$&$\Sigma$&$\Sigma$&$x_i^6$\\\hline
\multicolumn{1}{l}{} &0&1&2&3&4&5&6\\\cline{2-8}
\multicolumn{1}{l}{} &\multicolumn{7}{c}{$i$}
\end{tabular}
\end{center}
\end{document}
So, in place of the ∑ summation symbols, I wish to actually specify a particular equation and have Texifier do the calculation, depending on the value of the index "i" of x. I have a particular set of numbers I am working with, and essentially a binary operation that applies one of two rules depending on the index value of the term in the set. That's the part that I have no idea where to begin with. Messing around with the different examples, I am kind of beginning to understand how the language works. Also waiting on Tex by Topic and The Texbook in the mail. Should be fruitful reading.

I would kindly oblige you on the review, but I actually do not have an amazon account.
User avatar
Stefan Kottwitz
Site Admin
Posts: 10343
Joined: Mon Mar 10, 2008 9:44 pm

Re: Help: Creating Pascal-esque triangle (different structure and numbers) with TikZ for academic paper

Post by Stefan Kottwitz »

The TeXbook and TeX by Topic are great books, for understanding the background and the history. As an author using LaTeX, one may not need it. But it's good reading stuff, and helps with a deeper understanding of macro programming.

LaTeX (and TeX) are primarily for typesetting, nicely presenting. They are not calculators. There are additional tools and packages for doing calculations and embedding results in code for displaying with LaTeX, but that's some extra effort of course. TikZ (pgfmath) is good, or the fp package. LaTeX can also process csv format files with externally calculated data. LuaTeX can use Lua math features. I used it in some examples here: pgfplots.net/tag/luatex. I used pgfmath for the Pascal triangle here on X. That's rather complicated. LuaTeX is easier once it's understood. It means much time for a single table though - it's great to learn this, but if there's time pressure, it's ok to take over data from Excel into the LaTeX document.

Stefan
LaTeX.org admin
spe420
Posts: 6
Joined: Tue Jun 03, 2025 8:52 am

Re: Help: Creating Pascal-esque triangle (different structure and numbers) with TikZ for academic paper

Post by spe420 »

I see. That makes sense. This certainly betrays my unfamiliarity with the language. Just to be exhaustive, I have these other two examples of code that I am basing my thoughts off of. So, for starters there is this example:

Code: Select all

\documentclass{article}
\usepackage{tikz}

\makeatletter
\newcommand\binomialCoefficient[2]{%
    % Store values 
    \c@pgf@counta=#1% n
    \c@pgf@countb=#2% k
    %
    % Take advantage of symmetry if k > n - k
    \c@pgf@countc=\c@pgf@counta%
    \advance\c@pgf@countc by-\c@pgf@countb%
    \ifnum\c@pgf@countb>\c@pgf@countc%
        \c@pgf@countb=\c@pgf@countc%
    \fi%
    %
    % Recursively compute the coefficients
    \c@pgf@countc=1% will hold the result
    \c@pgf@countd=0% counter
    \pgfmathloop% c -> c*(n-i)/(i+1) for i=0,...,k-1
        \ifnum\c@pgf@countd<\c@pgf@countb%
        \multiply\c@pgf@countc by\c@pgf@counta%
        \advance\c@pgf@counta by-1%
        \advance\c@pgf@countd by1%
        \divide\c@pgf@countc by\c@pgf@countd%
    \repeatpgfmathloop%
    \the\c@pgf@countc%
}
\makeatother

\begin{document} 
\begin{tikzpicture}
\foreach \n in {0,...,15} {
  \foreach \k in {0,...,\n} {
    \node at (\k-\n/2,-\n) {$\binomialCoefficient{\n}{\k}$};
  }
}
\end{tikzpicture}

\end{document}[/LaTeX]
And then the code from the original video I referred to in the first post:
[LaTeX]\documentclass{standalone}
\usepackage{tikz}
\usepgflibrary{fpu}

\begin{document}

\def\N{8}

\tikz[
x = 0.75 cm, y = 0.5 cm,
pascal node/.style={font = \footnotesize}
]
\path
\foreach \n in {0,...,\N} {
\foreach \k in {0,...,\n} {
(-\n/2+\k, -\n) node [pascal node/.try] {
\pgfkeys{/pgf/fpu}
\pgfmathparse{round(\n!/(\k!*(\n-\k)!))}
\pgfmathfloattoint{\pgfmathresult}
\pgfmathresult
}
}
};
\end{document}
I don't fully understand all of the code, but I see that certain things are defined, for example "pascal node", and referred to. And yes, as you say, that pgf does the calculations for as many iterations of the variable \N as it is told to. I am completely unfamiliar with scripting in lua, or any programming language for that matter. I don't really have any time constraints. This is more so a hobby project than anything else, though I am putting a serious effort into it to make it as professional as possible a presentation. I don't particularly mind having to labor over the finer details, but I don't really know where to start if, say, I wanted to define my own function and do calls to it for an Nth row of my variant of the structure. I can of course manually insert the values now that I have a basic grasp, but I want to use this as an opportunity to learn something new. Appreciate the feedback thus far. Many thanks.
Last edited by spe420 on Sun Jul 06, 2025 12:15 am, edited 1 time in total.
spe420
Posts: 6
Joined: Tue Jun 03, 2025 8:52 am

Re: Help: Creating Pascal-esque triangle (different structure and numbers) with TikZ for academic paper

Post by spe420 »

Would you please supply the code for the example you posted on X? I would be grateful if you would please do so. I have just tried copying it off of the image, but I am getting several errors within the first few lines.
User avatar
Stefan Kottwitz
Site Admin
Posts: 10343
Joined: Mon Mar 10, 2008 9:44 pm

Re: Help: Creating Pascal-esque triangle (different structure and numbers) with TikZ for academic paper

Post by Stefan Kottwitz »

Found it:

Code: Select all

\documentclass[tikz,border=50pt]{standalone}%
\usepackage{ifthen,amsmath}
\let\result\relax
\makeatletter
\newcommand\binomialCoefficient[2]{%
    \c@pgf@counta=#1% n
    \c@pgf@countb=#2% k
    \c@pgf@countc=\c@pgf@counta%
    \advance\c@pgf@countc by-\c@pgf@countb%
    \ifnum\c@pgf@countb>\c@pgf@countc%
        \c@pgf@countb=\c@pgf@countc\fi%
    \c@pgf@countc=1% will hold the result
    \c@pgf@countd=0% counter
    \pgfmathloop% c -> c*(n-i)/(i+1) for i=0,...,k-1
        \ifnum\c@pgf@countd<\c@pgf@countb%
        \multiply\c@pgf@countc by\c@pgf@counta%
        \advance\c@pgf@counta by-1%
        \advance\c@pgf@countd by1%
        \divide\c@pgf@countc by\c@pgf@countd%
    \repeatpgfmathloop%
    \the\c@pgf@countc%
    \xdef\result{\the\c@pgf@countc}}
\makeatother
\begin{document}
\newdimen\R\R=.4cm
\newcommand\mycolor{gray}
\begin{tikzpicture}[line width=.8pt]
  \node[text centered] at (-3.5,-0.3) {$\begin{aligned}
      &\rlap{Catalan numbers:}\\
      C_n &= \frac{1}{n+1}{2n\choose n} = \frac{(2n)!}{(n+1)!\,n!} \\
          &= 1, 1, 2, 5, 14, 42, 132, \ldots\end{aligned}$};
  \node[shift={(0:{sqrt(3)*\R-8})},
    fill=white,inner sep=0pt,anchor=west,font=\tiny]{$=\mathbf{\color{red}1}$};
  \foreach \k in {0, ..., 12}{
    \begin{scope}[shift={(-60:{sqrt(3)*\R*\k})}]
      \pgfmathtruncatemacro\ystart{12-\k}
      \foreach \n in {0,...,\ystart}{
        \pgfmathsetmacro{\test}{\n == \k-2 ? 1 : 0}
        \pgfmathtruncatemacro\newn{\n+\k}
        \ifthenelse{\n=\k}{\def\mycolor{blue}}{}
        \ifthenelse{\test=1}{\def\mycolor{green}}{}
        \begin{scope}[shift={(-120:{sqrt(3)*\R*\n})}]
           \draw[top color=\mycolor!20, bottom color=\mycolor!60] 
             (30:\R) \foreach \x in {90, 150, ..., 330} {
             -- (\x:\R)}
             -- cycle (90:0)
             node {\tiny$\mathbf{\binomialCoefficient{\newn}{\k}}$};
             \ifthenelse{\n=\k}{\xdef\previous{\result}}{}
             \ifthenelse{\test=1}{
               \pgfmathtruncatemacro{\catalan}{\previous-\result}
               \node[xshift=-10,fill=white,inner sep= 0pt]{$-$};
               \node[shift={(0:{sqrt(3)*\R*(\k-1)-8})},
                 fill=white,inner sep= 0pt,anchor=west,font=\tiny]
                 {$\previous-\result=\mathbf{\color{red}\underline\catalan}$};
             }{}
         \end{scope}}
    \end{scope}}
\end{tikzpicture} 
\end{document}
Stefan
LaTeX.org admin
spe420
Posts: 6
Joined: Tue Jun 03, 2025 8:52 am

Re: Help: Creating Pascal-esque triangle (different structure and numbers) with TikZ for academic paper

Post by spe420 »

Great. Will post code here if/when successful.
spe420
Posts: 6
Joined: Tue Jun 03, 2025 8:52 am

Re: Help: Creating Pascal-esque triangle (different structure and numbers) with TikZ for academic paper

Post by spe420 »

So, random tangent, but upon trying to set the following code (from here: https://pgfplots.net/strange-attractors/) in Texifier, I receive an error for a line which, to my lying eyes, is not present in the document:

Code: Select all

\documentclass{standalone}
\usepackage{pgfplots,luacode}
\pgfplotsset{compat=1.18}
\usepgfplotslibrary{colormaps}
\usetikzlibrary{backgrounds}
\begin{luacode*}
  -- Differential equation
  function f(x,y,z)
    local a = 0.95
    local b = 0.7
    local c = 0.6
    local d = 3.5
    local e = 0.25
    local f = 0.1
    return {(z-b)*x-d*y, d*x+(z-b)*y,
      c+a*z-z^3/3-(x^2+y^2)*(1+e*z)+f*z*x^3}
  end
  -- Write PGFplots data as coordinates
  function print_Attractor(h,npoints,option)
    -- The initial point (x0,y0,z0)
    local x0 = 0.0
    local y0 = 1.0
    local z0 = 0.0
    -- Add random number between -0.25 and 0.25
    local x = x0 + (math.random()-0.5)/2
    local y = y0 + (math.random()-0.5)/2
    local z = z0 + (math.random()-0.5)/2
    tex.sprint("\\addplot3[".. option .."] coordinates{")
    -- dismiss first 100 points to go into the attractor
    for i=1, 100 do
      m = f(x,y,z)
      x = x + h * m[1]
      y = y + h * m[2]
      z = z + h * m[3]
    end
    for i=1, npoints do
      m = f(x,y,z)
      x = x + h * m[1]
      y = y + h * m[2]
      z = z + h * m[3]
      tex.sprint("("..x..","..y..","..z..")")
    end
    tex.sprint("}")
  end
\end{luacode*}
\newcommand\addAttractorPlot[3][]{%
  \directlua{print_Attractor(#2,#3,[[#1]])}}
\begin{document}
\begin{tikzpicture}
  \begin{axis}[hide axis, axis equal,
      zmin = 0, zmax = 1,
      show background rectangle,
      /tikz/background rectangle/.style = {
      left color = black, right color = black!20,
      shading angle = 135}]
  \foreach \i in {1,...,10}% step h=0.015, 2000 points:
    \addAttractorPlot[color of colormap=100*\i]
      {0.015}{2000};
  \end{axis}
\end{tikzpicture}
\end{document}
I get the following three errors on line 1, despite having left it unaltered from the source:

no.1:
***
! Undefined control sequence.
l.1 \usepackage
{pgfplots,lua-visual-debug}}
! Too many }'s.
l.1 \usepackage{pgfplots,lua-visual-debug}}
***
no.2:
***
! Undefined control sequence.
l.1 \usepackage
{pgfplots,lua-visual-debug}}
! Too many }'s.
l.1 \usepackage{pgfplots,lua-visual-debug}}
***
no.3:
***
! Undefined control sequence.
l.1 \usepackage
{pgfplots,lua-visual-debug}}
! Too many }'s.
l.1 \usepackage{pgfplots,lua-visual-debug}}
***
Any suggestions? Have I misunderstood something?
Post Reply