为什么pgfTikZ
计算精度会失败?
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\def\Radio{10}
\pgfmathsetmacro\cRadio{pow(\Radio,2)}
\pgfmathapproxequalto{\cRadio}{int(\cRadio)}
\ifpgfmathcomparison
\pgfmathtruncatemacro{\tcRadio}{\cRadio}%integer
\else
\pgfmathsetmacro{\tcRadio}{\cRadio}%decimal
\fi
\pgfmathsetmacro\rArea{\tcRadio*pi}
\pgfmathsetmacro\all{(\Radio^2)*pi}
\node[right] at (0,4) {$R=$ \Radio};
\node[right] at (0,3) {$R^2=$ \cRadio};
\node[right] at (0,2) {$R^2\approx$ \tcRadio};
\node[right] at (0,1) {Area: \rArea}; %314.15863
\node[right] at (0,0) {Area: \all}; %314.15863
\node[right] at (0,-1) {Correct: 314.1592654};
\end{tikzpicture}
\end{document}
答案1
因为pgfmath
是不是准确。改用xfp
。我保留了\rArea
所有计算出的数字,并四舍五入\all
到小数点后七位,只是为了展示它的工作原理。
\documentclass{article}
\usepackage{tikz}
\usepackage{xfp}
\begin{document}
\begin{tikzpicture}
\def\Radio{10}
\edef\cRadio{\fpeval{\Radio**2}}
\ifpgfmathcomparison
\edef\tcRadio{\fpeval{trunc(\cRadio,0)}%integer
\else
\let\tcRadio\cRadio %decimal
\fi
\edef\rArea{\fpeval{\tcRadio*pi}}
\edef\all{\fpeval{round(\Radio^2*pi,5)}}
\node[right] at (0,4) {$R= \Radio$};
\node[right] at (0,3) {$R^2= \cRadio$};
\node[right] at (0,2) {$R^2\approx \tcRadio$};
\node[right] at (0,1) {Area: $\rArea$}; %314.15863
\node[right] at (0,0) {Area: $\all$}; %314.15863
\node[right] at (0,-1) {Correct: 314.1592654};
\end{tikzpicture}
\end{document}