将随机 \frac{a}{b} 转换为浮点数?问题表述得是否正确?

将随机 \frac{a}{b} 转换为浮点数?问题表述得是否正确?

如何将 [字符串?] 形式中随机选择的分数转换\frac{a}{b}为 [浮点数?] 形式,以便pgf可以用它进行计算?

我正在创建一个练习,让学生练习确定随机生成的线的方程。

首先选择一个随机分数作为斜率。该分数在方程中按预期显示,但我认为它不能用于计算图中的 y 值TikZ

我该如何解决?

\documentclass{article}

\usepackage{pgf}
 \pgfmathsetseed{\number\pdfrandomseed}
\usepackage{pgffor}
\usepackage{tikz}

\pgfmathdeclarerandomlist{FracSlopes}
{%
 {\frac{1}{2}}
 {\frac{3}{2}}
 {\frac{5}{2}}
 {\frac{7}{2}}
 {\frac{1}{3}}
 {\frac{2}{3}}
 {\frac{4}{3}}
 {\frac{5}{3}}
 {\frac{7}{3}}
}

\pgfmathrandomitem{\FracSlope}{FracSlopes}




\begin{document}

% Since the line below works
% I know the fraction is being selected randomly.
\(y=\FracSlope{x}\) 

\begin{tikzpicture}[scale=0.3]
\draw[help lines, gray, thin] (-10,-10) grid (10,10);
\draw[very thick,<->] (-10.3,0)--(10.3,0);
\draw[very thick,<->] (0,-10.3)--(0,10.3);
%
% Everythig compiles if the next two lines are commented out.
\clip (-10,-10) rectangle (10,10);
 \draw[blue, very thick, domain=-10:10] plot (\x,\FracSlope*\x);
 % It's interpreting \FracSlope as a string, not a number.
 % I'm *pretty* sure that's the problem.
\end{tikzpicture}

\end{document}

答案1

您不能\frac在计算上下文中使用。但您可以以间接方式使用它。

\documentclass{article}

\usepackage{tikz}

\pgfmathsetseed{\number\pdfrandomseed}

\pgfmathdeclarerandomlist{FracSlopes}
{%
 {\rfrac{1}{2}}
 {\rfrac{3}{2}}
 {\rfrac{5}{2}}
 {\rfrac{7}{2}}
 {\rfrac{1}{3}}
 {\rfrac{2}{3}}
 {\rfrac{4}{3}}
 {\rfrac{5}{3}}
 {\rfrac{7}{3}}
}

\pgfmathrandomitem{\FracSlope}{FracSlopes}

\newcommand{\rfrac}{\frac}
\newcommand{\computefrac}[2]{(#1/#2)}


\begin{document}

% Since the line below works
% I know the fraction is being selected randomly.
\(y=\FracSlope x\) 

\begin{tikzpicture}[scale=0.3]
\let\rfrac\computefrac
\draw[help lines, gray, thin] (-10,-10) grid (10,10);
\draw[very thick,<->] (-10.3,0)--(10.3,0);
\draw[very thick,<->] (0,-10.3)--(0,10.3);
%
% Everythig compiles if the next two lines are commented out.
\clip (-10,-10) rectangle (10,10);
 \draw[blue, very thick, domain=-10:10] plot (\x,{\FracSlope*\x});
\end{tikzpicture}

\end{document}

在此处输入图片描述

为什么要这样间接?由于这些分数需要在不同的上下文中使用,并具有不同的输出,因此最好使用特殊命令来命名它们,\frac除非\let\rfrac\computefrac发出,否则将其设置为扩展为(这将在组中保留)。您仍然可以\fractikzpicture环境中使用,因为这不受重新定义的影响。

相关内容