tikz-pgfplot 中 int() 函数的奇怪结果

tikz-pgfplot 中 int() 函数的奇怪结果

也许我在 tikz-pgfplot 中发现了一个新的错误。你能确认这个奇怪的结果吗:

\pgfmathparse{int(11/2)}

返回 0

@喷射

这是我的一段代码,它产生了这个问题int()

\documentclass{article}

\usepackage{pgfplots}
\pgfplotsset{compat=1.18}

\begin{document}
    \pgfmathparse{int(11/2)}
    \pgfmathresult %correctly returns 5 as JeT said, but
    
\begin{figure} % this plot is wrong as int(11/2) returns 0 for instance
    \centering
    \begin{tikzpicture}[
        scale=1.0,
        declare function={
            bit(\c,\i)=int(\c/2^\i)-2*int(\c/2^(\i+1)); %Compute the n-th binary digit of c. Both n and c must be integers
        }
        ]
        \begin{axis}[
            width=10 cm,
            height=6 cm,
            xlabel = {\large $C$},
            ylabel = {\large digit 0 of $C$},
            minor tick num=5,
            xmajorgrids,
            ymajorgrids,
            xmin = 0,
            xmax = 20,
            ymin = 0,
            ymax = 1,
            ]
            \addplot [samples at={0,...,20}, ycomb, mark=*] {bit(x,0)}; % check for debugging purpose
        \end{axis}
    \end{tikzpicture}
    \caption{Test int()}
    \label{fig:Test int()}
\end{figure}
    
\end{document}

我知道哪里出了问题。

答案1

在环境中采用循环的不同方法axis

在此处输入图片描述

\documentclass{standalone}
%\documentclass{article}

\usepackage{pgfplots}
\pgfplotsset{compat=1.18}

\begin{document}

% \begin{figure}
%     \centering
    \begin{tikzpicture}[
        scale=1.0,
        declare function={
            bit(\c,\i)=int(\c/2^\i)-2*int(\c/2^(\i+1)); %Compute the n-th binary digit of c. Both n and c must be integers
        }
    ]
        \begin{axis}[
            width=10 cm,
            height=6 cm,
            xlabel = {\large $C$},
            ylabel = {\large digit 0 of $C$},
            minor tick num=5,
            xmajorgrids,
            ymajorgrids,
            xtick={0,...,20},
            ytick={0,1},
            xmin = 0,
            xmax = 20,
            ymin = 0,
            ymax = 1,
            ]
            \foreach \x in {0,...,20}{% here you'll use a loop in the axis
                \pgfmathparse{bit(\x,0)}
                \edef\temp{\noexpand\addplot coordinates {(\x, \pgfmathresult)};}
                \temp
            }
        \end{axis}
    \end{tikzpicture}
%     \caption{Test int()}
%     \label{fig:Test int()}
% \end{figure}

\end{document}

相关内容