获取线段长度,不同尺度下结果不一样

获取线段长度,不同尺度下结果不一样

我有一个宏 \mylengthcm 来获取线段的长度。但不同比例下的结果不一样。我该怎么做才能得到相同的结果?谢谢你的帮助。这是我的代码

\documentclass{article}
\usepackage{tikz,tkz-euclide}
\usepackage{xfp}
\makeatletter
\def\mylengthcm(#1,#2)#3{%
    \pgfpointdiff{\pgfpointanchor{#1}{center}}%
                 {\pgfpointanchor{#2}{center}}%
    \edef\xfpdodaipt{\fpeval{sqrt((\pgf@x)^2+(\pgf@y)^2)}}
    %pt to cm
    \pgfmathparse{\xfpdodaipt pt/1cm}
    \edef\xfpdodaicm{\fpeval{round(\pgfmathresult,7)}}
    \global\expandafter\edef\csname #3\endcsname{\xfpdodaicm}
    }%%
\makeatother
\begin{document}
\begin{tikzpicture}[font=\small,scale=.5]
\draw[help lines] (-6,-6) grid (6,6);
\coordinate (A) at (0,0);
\coordinate (B) at (3,4);
\mylengthcm(A,B){rcm} 
\draw[teal](A)--(B)node[midway, sloped, below]{$\rcm$ cm};
\draw[teal] (A)circle(\rcm);
\end{tikzpicture}
%
\begin{tikzpicture}[font=\small,scale=0.8]
\draw[help lines] (-6,-6) grid (6,6);
\coordinate (A) at (0,0);
\coordinate (B) at (3,4);
\mylengthcm(A,B){rcm}
\draw[teal](A)--(B)node[midway, sloped, below]{$\rcm$ cm};
\draw[teal] (A)circle(\rcm);
\end{tikzpicture}
\newline
%\usepackage{tkz-euclide}
\begin{tikzpicture}[scale=2]
    \tkzDefPoint(0,0){A}
    \tkzDefPoint(3,4){B}
    \tkzCalcLength(A,B)\tkzGetLength{dAB}
    \tkzCalcLength[cm](A,B)\tkzGetLength{rAB}
%%%%%
    \draw(A)--(B)node[midway, sloped, above]
        {$\dAB \mathrm{pt}$ = $\rAB \mathrm{cm}$};
    \foreach \p/\pos in {A/-90,B/-90}
        \fill(\p)circle(1.pt)node[shift={(\pos:8pt)}]{$\p$};
\end{tikzpicture}
\end{document}

答案1

这是适用于任意缩放的一种方法。如你所见,计算的误差约为10^{-4},就像 TeX 的计算一样。

在此处输入图片描述

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
% from https://www.facebook.com/groups/TikZandAsymptote 
% \tikzlength(A,B)(\c) >> \c is the length in cm of AB
\def\tikzlength(#1,#2)(#3){%
\path let \p1 = ($(#1)-(#2)$),
          \n1 = {scalar(veclen(\x1,\y1)/1cm)}
in \pgfextra{\xdef#3{\n1}};
}%
\begin{tikzpicture}
\path
(0,0) coordinate (A)    
(4,0) coordinate (B)
(0,3) coordinate (C)
;
\draw (C)--(A)--(B);
\tikzlength(B,C)(\a)
\draw[blue] (B)--(C) node[sloped,above,midway]{$\a$ cm};
\end{tikzpicture}
\begin{tikzpicture}[scale=.5]
    \path
    (0,0) coordinate (A)    
    (4,0) coordinate (B)
    (0,3) coordinate (C)
    ;
    \draw (C)--(A)--(B);
    \tikzlength(B,C)(\a)
    \draw[red] (B)--(C) node[sloped,above,midway]{$\a$ cm};
\end{tikzpicture}

\end{document}  

PS:在 Asymptote 中,有一个内置函数length(与 相同abs)可计算二维和三维点的长度。Asymptote 的精度约为10^{-18}(?)。

在此处输入图片描述

unitsize(1cm);
pair A=(0,0), B=(4,0), C=(0,3);
real a=length(B-C);

picture pic1,pic2;

draw(pic1,C--A--B);
draw(pic1,Label(string(a)+" cm"),B--C,magenta);
add(pic1);

draw(pic2,C--A--B);
draw(pic2,Label(string(a)+" cm"),B--C,purple);
add(shift(5,0)*scale(.5)*pic2);

shipout(bbox(5mm,invisible)); 

相关内容