\documentclass[fleqn,dvipsnames]{article}
\usepackage[a4paper,margin=1.7cm]{geometry}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{xparse}
\usepackage[np,autolanguage]{numprint}
\usepackage{xintexpr}
\usepackage{pst-plot}
\usepackage{kpfonts}

\parindent0pt
\parskip4pt
\thispagestyle{empty}

%% Declare some math operators
\DeclareMathOperator\Var{Var}
\DeclareMathOperator\Expect{E}
\DeclareMathOperator\Prob{P}

\catcode`_ 11
\def\onlyfirsti#1{\xint_firstoftwo{#1}}
\def\onlysecondi#1{\xint_secondoftwo{#1}}
\catcode`_ 8
\def\onlyfirst#1{\onlyfirsti#1}
\def\onlysecond#1{\onlysecondi#1}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%           CONVERSION MACROS FOR A GIVEN SPACE SEPARATED LIST             %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% ORIGINAL MACRO BY DPS -- ready made for "expected value":                %%
%% Begin ---- dps                                                           %%
%% Embrace each single element of the list                                  %%
%% AND                                                                      %%
%% additionally embrace them again in pairs                                 %%
%% AMAZING ...                                                              %%
%%  \makeatletter                                                           %%
%%  \newtoks\myToks \myToks={}                                              %%
%%  \def\convertToListWithBraces#1{\myToks={}\expandafter\myMacroi#1 ; ; }  %%
%%  \def\myMacroi#1 #2 {\if#1;\def\donext{\myMacroii}\else                  %%
%%  \edef\x{\the\myToks{{#1}{#2}}}\myToks=\expandafter{\x}                  %%
%%  \def\donext{\myMacroi}\fi\donext}                                       %%
%%  \def\myMacroii{\edef\listeTc{\the\myToks}}                              %%
%%  \makeatother                                                            %%
%% End ---- dps                                                             %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%             DERIVATIONS FROM THOMAS OF THE MACRO ABOVE                   %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%% Convert a given space separated list to a list
%% There all elements are braced and then these braced elements are dditionally braced in groups of two
%%
%% {a1 b1 a2 b2 a3 b3 ...} --> { { {\macro{a1}} {b1} } { {\macro{a2}} {b2} } { {\macro{a3}} {b3} } ...}
%%
%% FOR "EXPECTED VALUE"
\makeatletter
\newtoks\ToksCWDB \ToksCWDB={} \def\SC{;}
\def\convertToListWithBraces#1 {\ToksCWDB={}\expandafter\ListWithBracesi#1 ; ; }
\def\ListWithBracesi#1 #2 {\def\argDBi{#1}\ifx\argDBi\SC\def\donextCWDB{\ListWithBracesii}\else
    \edef\xdb{\the\ToksCWDB{{#1}{#2}}}\ToksCWDB=\expandafter{\xdb}
    \def\donextCWDB{\ListWithBracesi}\fi\donextCWDB}
\makeatother

%% Convert a given space separated list to a list
%% There all elements braced "SingleBraced"  --> SB
%%  all elements are calculated well to be used with PostScript
%%
%% {a1 b1 a2 b2 a3 b3 ...} --> { {\macroCalcPS{a1}} {\macroCalcPS{b1}} {\macroCalcPS{a2}} {\macroCalcPS{b2}} {\macroCalcPS{a3}} {\macroCalcPS{b3}} ...}
%%
%% FOR "PSTRICKS"
\makeatletter
\newtoks\ToksSB \ToksSB={} \def\SC{;}
\def\ConvertToListSB#1{\ToksSB={}\expandafter\ConvertToListSBi#1 ; }
\def\ConvertToListSBi#1 {\def\argSBi{#1}\ifx\argSBi\SC\def\donextSB{\ConvertToListSBii}\else
\edef\xsb{\the\ToksSB{\macroCalcPS{#1}}}\ToksSB=\expandafter{\xsb}
\def\donextSB{\ConvertToListSBi}\fi\donextSB}
\makeatother

%% FOR "VARIANCE"
\makeatletter
\newtoks\VarToks \VarToks={} \def\SC{;}
\def\convertToVarList#1{\VarToks={}\expandafter\Variancei#1 ; ; }
\def\Variancei#1 #2 {\def\argVari{#1}\ifx\argVari\SC\def\donextVar{\Varianceii}\else
\edef\xvar{\the\VarToks{{(#1-\mueVar)^2}{#2}}}\VarToks=\expandafter{\xvar}
\def\donextVar{\Variancei}\fi\donextVar}
%\def\Varianceii{\edef\listeVar{\the\VarToks}}
\makeatother


\newcommand{\GenerateProbListsi}[2]{\expandafter\def\expandafter#1{#2}}

\makeatletter
\newcommand{\GenerateProbLists}[2]{%
% Definition of the original list:
\expandafter\GenerateProbListsi\expandafter{\csname #1\endcsname}{#2}
% Conversion to other formatted lists:
\converteList{#1}}
\makeatother

\makeatletter
\newcommand{\converteList}[1]{%
\expandafter\let\expandafter\myliste@noB\csname #1\endcsname
\def\ListWithBracesii{\edef\liste@DB{\the\ToksCWDB}}%
\@namedef{#1DB}{\liste@DB}
\convertToListWithBraces{\myliste@noB} % <-- space after convertToListWithBraces??
                                       % --> gives a new list with name \LPDB:
                                       %     all items are braced in groups of two and every single item of this pair is braced
\def\ConvertToListSBii{\edef\liste@SB{\the\ToksSB}}%
\@namedef{#1PST}{\xintListWithSep{ }{\liste@SB}}%
\ConvertToListSB{\myliste@noB}%        % --> gives a new list with name \LPDBSB:
                                       %     all single items are braced
                                       % --> this is for \listplot from "pst-plot"
\xintdefvar mue_#1 := \xinttheexpr reduce(\xintListWithSep{+}{\xintApply{\macroMul}{\@nameuse{#1DB}}})\relax ;
\def\mueVar{\xinttheexpr mue_#1\relax}%
\def\expVal{\xintifSgn{\xinttheexpr mue_#1\relax}{+\macroFrac{abs(mue_#1)}}{-\macroFrac{mue_#1}}{-\macroFrac{mue_#1}}}%  %% Define expected Value
\def\Varianceii{\edef\liste@Var{\the\VarToks}}%
\@namedef{#1Var}{\liste@Var}%
\convertToVarList{\myliste@noB}%       % --> gives a new list with name \LPVar:
                                       %     this is for calculating the variance
\xintdefvar sigma_#1 := \xinttheexpr reduce(\xintListWithSep{+}{\xintApply{\macroMul}{\@nameuse{#1Var}}})\relax;
%\expandafter\let\expandafter\liste@DB\csname #1DB\endcsname
\xintdefvar NrOBr_#1 := \expandafter\xintLength\expandafter{\liste@DB};
}
\makeatother


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% FORMATTING and CALCULATION MACROS %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\newcommand{\fracforList}{\def\macroFrac##1{\xintSignedFrac{\xinttheexpr reduce(##1)\relax}}}
\newcommand{\decimalforList}[1][4]{\def\macroFrac##1{\np{\xintDecToString{\xintREZ{\xinttheiexpr[#1] reduce(##1)\relax}}}}}
%% Commands to switch between FRACTION output or DECIMAL output:
\fracforList
%\decimalforList

\def\macroFracBracket#1{\xintifSgn{\xinttheexpr #1 \relax}{\left(\macroFrac{#1}\right)}{\macroFrac{#1}}{\macroFrac{#1}}} %
\def\macroCalc#1{\xinttheexpr reduce(#1)\relax}
\def\macroFraccdotBracket#1{\xintListWithSep{\cdot }{\xintApply{\macroFracBracket}{#1}}}
\def\macroMulSgn#1{\xintifSgn{\xinttheexpr \xintListWithSep{*}{\xintApply{\macroCalc}{#1}}\relax}
                        {\left(\macroFrac{\xintListWithSep{*}{\xintApply{\macroCalc}{#1}}}\right)}
                        {\macroFrac{\xintListWithSep{*}{\xintApply{\macroCalc}{#1}}}}
                        {\macroFrac{\xintListWithSep{*}{\xintApply{\macroCalc}{#1}}}}}
\def\macroMul#1{\xinttheexpr reduce(\xintListWithSep{*}{#1})\relax}
\def\macroFraccdot#1{\xintListWithSep{\cdot}{\xintApply{\macroFrac}{#1}}}
\def\macroFraccdotBracketV#1{\xintListWithSep{\cdot}{#1}}
\def\macroFraccdotBracketVFrac#1{\xintListWithSep{\cdot\macroFrac}{#1}}
%% Variance formatting
\def\macroFraccdotBracketVar#1{\left(\xintListWithSep{\expVal\right)^2\cdot }{\xintApply{\macroFrac}{#1}}}
%% PostScript calculating
\def\macroCalcPS#1{\xintDecToString{\xintREZ{\xinttheiexpr[6] reduce(#1)\relax}}}

%% For "variance" especially:
%% If the number of list elements increases, the formula for the variance
%% definitely breaks across lines. A challenge occurs so!!!
%% Using "breqn" package (with its automatic line breaks in display mode) does not satisfy our needs.
%% Following comes along a macro that will split the list into fragments for the desired output of the customer
%% how many x_i per line within the formula -- setup with amsmath's "align*" environment.
%% Highly customizing the "\xintKeep" macro from "xint" package -- see pages 186++ within the "xint.pdf v 1.3f".
%% Many thanks for that package go to Guru Bubu :-)
%% A hard nut to crack was the "\@namedef{#2\romannumeral\@tempa}" to expand correctly within the "\xintFor" loop ...
\makeatletter
\newcommand{\listSplitting}[3]{%
    \def\@tempa{0}\def\@tmpSum{0}%%
    \xintFor ##1 in {#1}\do%
          {%
            \edef\@tempa{\xintiieval{1+\@tempa}}%
            \edef\@tmpSum{\xintiieval{##1+\@tmpSum}}%
            \begingroup\edef\x{\endgroup
            \global\noexpand\@namedef{#2\romannumeral\@tempa}{\xintKeep{\xintiieval{-##1}}{\xintKeep{\xintiieval{\@tmpSum}}{#3}}}}\x
          }%
}
\makeatother

\title{Probabilités : calculs avec \texttt{xint} -- illustrations avec \texttt{PSTricks}}
\date{1 janvier 2020}
\author{%
        Thomas \textsc{Söll}\kern4em
        Jürgen \textsc{Gilg}\\
        {\small Remerciements à Jean-Fran\c{c}ois~\textsc{Burnol} et à D.~P.~\textsc{Story}~!}
       }

\begin{document}

\maketitle


%% For testing, some values were chosen negative, to see the formatting with parentheses :-)
%% The following command defines the following commands with the BASE-NAME "\LP":
%% \LPDB, \LPSB, \LPVar, \LPPST
%%
%% Suffixes:
%%     -DB (DoubleBraced)                  -- so \LPDB,
%%     -SB (SingleBraced)                  -- so \LPSB,
%%     -Var (for variance)                 -- so \LPVar,
%%     -PST (for bar plot with PSTricks)   -- so \LPPST
%%
%% The freshly generated lists are ready made for diverse purposes

\GenerateProbLists{LP}{2 1/36 3 2/36 4 3/36 5 4/36 6 5/36 7 1/6 8 5/36 9 4/36 10 3/36 11 2/36 12 1/36}
%% NOTE:
% We know, this is a Binomial-Distribution and we could calculate each value and the complete list with xint
% predefined commands, but within this document we want to calculate with differently given values as well!
% For especially Binomial-Distributions we will write another article.


\section{Probabilité}

Donner la liste suivante des couples $x_i|\Prob(X=x_i)$ : ces valeurs ne sont séparées que par des espaces.

\medskip

{\small\color{Green}\verb!\GenerateProbLists{LP}{!\LP \}}


\subsection{Table des éléments de la liste}

\begin{center}%
%% Number of columns for the values x_i is auto-calculated: \xintiieval{NrOBr_LP}
\begin{tabular}{|c|*{\xintiieval{NrOBr_LP}}{c|}}
    \hline
    \vrule height 3ex depth 1.5ex width 0pt\relax %%%%%%%%
    $x_{i}$           \xintFor* #1 in {\LPDB} \do {&\bfseries \onlyfirst{#1}}\\
    \hline
    \vrule height 4.5ex depth 3ex width 0pt\relax
    $\Prob(X=x_{i})$  \xintFor* #1 in {\LPDB} \do %%%%%%%%
      {&$\displaystyle\xintSignedFrac{\macroCalc{\onlysecond{#1}}}$}\\
    \hline
\end{tabular}
\end{center}
{\small\color{Green}
\begin{verbatim}
\begin{tabular}{|c|*{\xintiieval{NrOBr_LP}}{c|}}
    \hline
    \vrule height 3ex depth 1.5ex width 0pt\relax %%%%%%%%
    $x_{i}$           \xintFor* #1 in {\LPDB} \do {&\bfseries \onlyfirst{#1}}\\
    \hline
    \vrule height 4.5ex depth 3ex width 0pt\relax
    $\Prob(X=x_{i})$  \xintFor* #1 in {\LPDB} \do %%%%%%%%
      {&$\displaystyle\xintSignedFrac{\macroCalc{\onlysecond{#1}}}$}\\
    \hline
\end{tabular}
\end{verbatim}}


\subsection{Espérance}

\begin{equation*}
\Expect(X) = \xintiloop [1+1]
\expandafter\def\expandafter\tmp\xintbracediloopindex
x_\tmp\cdot \Prob(X=x_\tmp )
\ifnum \xintiloopindex < 2 + \repeat + \cdots = \mu
\end{equation*}
%
%% TYPE OUT DIVERSE LISTS WITHIN THE LOG FILE
%% Uncomment to view them in the log
%\typeout{-->!!\LPDB}
%\typeout{-->!!!\LPVar}
%\typeout{-->!!!!\LPPST}
%
On calcule automatiquement la valeur de l'espérance, pas à pas :
\begin{align*}
\Expect(X)  &= \xintListWithSep{+}{\xintApply{\macroFraccdotBracket}{\LPDB}}\\
            &= \xintListWithSep{+}{\xintApply{\macroMulSgn}{\LPDB}}%
             = \xintSignedFrac{\xinttheexpr mue_LP\relax} %\approx \np{\xintDecToString{\xintREZ{\xinttheiexpr[3] mue_LP\relax}}}
\end{align*}
{\small\color{Green}
\begin{verbatim}
\begin{align*}
\Expect(X)  &= \xintListWithSep{+}{\xintApply{\macroFraccdotBracket}{\LPDB}}\\
            &= \xintListWithSep{+}{\xintApply{\macroMulSgn}{\LPDB}}%
             = \xintSignedFrac{\xinttheexpr mue_LP\relax}%
            %\approx \np{\xintDecToString{\xintREZ{\xinttheiexpr[3] mue_LP\relax}}}
\end{align*}
\end{verbatim}}


\subsection{Variance}

\begin{equation*}
\Var(X) = \xintiloop [1+1]
\expandafter\def\expandafter\tmp\xintbracediloopindex
(x_\tmp-\mu)^2\cdot \Prob(X=x_\tmp )
\ifnum \xintiloopindex < 2 + \repeat + \cdots = \sigma^2
\end{equation*}
On calcule automatiquement la variance -- pas à pas :
%
%% Prepare the line breaks for the "align*" environment:
%% The comma separated list (6,5) tells:
%% First row 6 x_i
%% Second row 5 x_i
\listSplitting{6,5}{ListPart}{\LPDB}
\listSplitting{6,5}{LBreakVar}{\LPVar}
%
\begin{align*}
\Var(X) & = \xintListWithSep{+}{\xintApply{\macroFraccdotBracketVar}{\ListParti}}\\
             &\qquad + \xintListWithSep{+}{\xintApply{\macroFraccdotBracketVar}{\ListPartii}}\\
%              &\qquad + \xintListWithSep{+}{\xintApply{\macroFraccdotBracketVar}{\ListPartiii}}\\
%              &\qquad + \xintListWithSep{+}{\xintApply{\macroFraccdotBracketVar}{\ListPartiv}}\\
              & = \xintListWithSep{+}{\xintApply{\macroFraccdot}{\LBreakVari}}\\
              &\qquad + \xintListWithSep{+}{\xintApply{\macroFraccdot}{\LBreakVarii}}\\
%              &\qquad + \xintListWithSep{+}{\xintApply{\macroFraccdot}{\LBreakVariii}}\\
              & = \macroFrac{sigma_LP} \approx \np{\xintDecToString{\xintREZ{\xinttheiexpr[3] sigma_LP\relax}}}
              \quad \Rightarrow\quad
              \sigma = \sqrt{\Var(X)} \approx \np{\xintDecToString{\xintREZ{\xinttheiexpr[3] reduce(sqrt(sigma_LP))\relax}}}
\end{align*}
{\small\color{Green}
\begin{verbatim}
%% Prepare the line breaks for the "align*" environment:
%% The comma separated list (6,5) tells:
%% First row 6 x_i
%% Second row 5 x_i
\listSplitting{6,5}{ListPart}{\LPDB}
\listSplitting{6,5}{LBreakVar}{\LPVar}
%
\begin{align*}
\Var(X) & = \xintListWithSep{+}{\xintApply{\macroFraccdotBracketVar}{\ListParti}}\\
             &\qquad + \xintListWithSep{+}{\xintApply{\macroFraccdotBracketVar}{\ListPartii}}\\
             & = \xintListWithSep{+}{\xintApply{\macroFraccdot}{\LBreakVari}}\\
             &\qquad + \xintListWithSep{+}{\xintApply{\macroFraccdot}{\LBreakVarii}}\\
             & = \macroFrac{sigma_LP} \approx \np{\xintDecToString{\xintREZ{\xinttheiexpr[3] sigma_LP\relax}}}
             \quad \Rightarrow\quad
             \sigma = \sqrt{\Var(X)}%
             \approx \np{\xintDecToString{\xintREZ{\xinttheiexpr[3] reduce(sqrt(sigma_LP))\relax}}}
\end{align*}
\end{verbatim}}


\subsection{Histogramme}

%% Defining the values for the "expected value" ready made for PSTricks (both PS way and TeX way)
\def\muePS{\xintDecToString{\xintREZ{\xinttheiexpr[6]mue_LP\relax}}}
\def\mueFr{\xintSignedFrac{\xinttheexpr mue_LP\relax}}

%% Bar plot
\begin{pspicture}(-1,0)(13,8)
\psgrid[subgriddiv=1,gridlabels=0,gridwidth=0.4pt](0,0)(13,8)
\uput[r](13,0){$x$}
\listplot[plotstyle=bar,barwidth=1.0cm,yunit=40,fillstyle=solid,fillcolor=cyan,opacity=0.75]{\LPPST}
\psaxes[ticksize=0 5pt,tickstyle=inner,Dy=0.025,dy=1,comma]{->}(0,0)(-0.25,0)(13,8)
\psline[linestyle=dashed,linecolor=magenta,linewidth=1.5pt](\muePS,-0.2)(\muePS,6.9)
\uput[-90](\muePS,-0.3){\textcolor{magenta}{$\mu=\mueFr$}}
\end{pspicture}

\newpage

{\small\color{Green}
\begin{verbatim}
%% Defining the values for the "expected value" ready made for PSTricks (both PS way and TeX way)
\def\muePS{\xintDecToString{\xintREZ{\xinttheiexpr[6]mue_LP\relax}}}
\def\mueFr{\xintSignedFrac{\xinttheexpr mue_LP\relax}}

%% Bar plot
\begin{pspicture}(-1,0)(13,8)
\psgrid[subgriddiv=1,gridlabels=0,gridwidth=0.4pt](0,0)(13,8)
\uput[r](13,0){$x$}
\listplot[plotstyle=bar,barwidth=1.0cm,yunit=40,fillstyle=solid,fillcolor=cyan,opacity=0.75]{\LPPST}
\psaxes[ticksize=0 5pt,tickstyle=inner,Dy=0.025,dy=1,comma]{->}(0,0)(-0.25,0)(13,8)
\psline[linestyle=dashed,linecolor=magenta,linewidth=1.5pt](\muePS,-0.2)(\muePS,6.9)
\uput[-90](\muePS,-0.3){\textcolor{magenta}{$\mu=\mueFr$}}
\end{pspicture}
\end{verbatim}}
\end{document} 