TikZ 繪製函數錯誤。 - 如何讓程式碼變得更好?

TikZ 繪製函數錯誤。 - 如何讓程式碼變得更好?

我們已經得到了這個 TikZ 程式碼,據說這給了 geogebra 不同的結果(https://artofproblemsolving.com/community/c68h3228155_need_help_with_tikz):

\begin{tikzpicture}[scale=.5]
\draw[->] (-3,0)--(5,0) node[below]{$x$};
\draw[->] (0,-7)--(0,3) node[left]{$y$};
\draw[thick, domain=-1.5:2] plot(\x, {2.8*\x^4+4.77*\x^3-5.47*\x^2-7.61*\x});
\end{tikzpicture}

asymptote 還提供了另一個結果,例如 TikZ,請參閱上面連結中的帖子#2。

TikZ 哪些方面可以做得更好?

答案1

問題在於-擴展時的擴展/優先權\x。您可以使用@Skillmon的解決方案或添加括號:

\documentclass[border=3.14,tikz]{standalone}

\begin{document}

\begin{tikzpicture}[scale=.5]
\draw[->] (-3,0)--(5,0) node[below]{$x$};
\draw[->] (0,-7)--(0,3) node[left]{$y$};
\draw[thick, red, domain=-1.5:2] plot(\x, {2.8*(\x)^4+4.77*(\x)^3-5.47*(\x)^2-7.61*(\x)});
\draw[thick, dotted, domain=-1.5:2] plot(\x, {2.8*\x*\x*\x*\x+4.77*\x*\x*\x-5.47*\x*\x-7.61*\x});
\end{tikzpicture}

\end{document}

在此輸入影像描述

如果這樣做,符號優先問題會更加明顯:

\documentclass[border=3.14,tikz]{standalone}

\begin{document}

\begin{tikzpicture}[scale=.5]
\draw[->] (-3,0)--(5,0) node[below]{$x$};
\draw[->] (0,-7)--(0,3) node[left]{$y$};
\draw[thick, red, domain=-1.5:2] plot(\x, {\x^2});
\draw[thick, dotted, domain=-1.5:2] plot(\x, {(\x)^2});
\end{tikzpicture}

\end{document}

在此輸入影像描述

看起來,當\x^2擴展且值為負(例如 -2)時,您會得到-2^2,它被解釋為-4

答案2

kZ 在指數函數方面有問題,請使用\x*\x*\x*\x代替\x^4等:

\documentclass[border=3.14,tikz]{standalone}

\begin{document}

\begin{tikzpicture}[scale=.5]
\draw[->] (-3,0)--(5,0) node[below]{$x$};
\draw[->] (0,-7)--(0,3) node[left]{$y$};
\draw[thick, domain=-1.5:2] plot(\x, {2.8*\x*\x*\x*\x+4.77*\x*\x*\x-5.47*\x*\x-7.61*\x});
\end{tikzpicture}

\end{document}

在此輸入影像描述

要進一步改進這一點:減少domain(在 x=2 時評估的函數等於 45.86),增加samples,並且可能使用smooth


\documentclass[border=3.14,tikz]{standalone}

\begin{document}

\begin{tikzpicture}[scale=.5]
\draw[->] (-3,0)--(5,0) node[below]{$x$};
\draw[->] (0,-7)--(0,3) node[left]{$y$};
\draw[thin, red, domain=-1.5:1.5, samples=101, smooth] plot(\x, {2.8*\x*\x*\x*\x+4.77*\x*\x*\x-5.47*\x*\x-7.61*\x});
\end{tikzpicture}

\end{document}

如果您的函數仍然存在數字問題(該函數不是這種情況,但可能會發生),您可能需要使用該pgfmath-xfp套件。它會稍微減慢你的繪圖速度,但是使用它定義的函數可以提供更好的解析度:

\documentclass[border=3.14,tikz]{standalone}

\usepackage{pgfmath-xfp}

\begin{document}

\begin{tikzpicture}[scale=.5]
\draw[->] (-3,0)--(5,0) node[below]{$x$};
\draw[->] (0,-7)--(0,3) node[left]{$y$};
\draw[red, domain=-1.5:1.5, samples=101, smooth] plot(\x, {2.8*\x*\x*\x*\x+4.77*\x*\x*\x-5.47*\x*\x-7.61*\x});
\pgfmxfpdeclarefunction{myfunction}{1}
  {2.8*(#1)^4+4.77*(#1)^3-5.47*(#1)^2-7.61*(#1)}
\draw[very thin, blue, domain=-1.5:1.5, samples=101,smooth] plot(\x, {myfunction(\x)});
\end{tikzpicture}

\end{document}

在此輸入影像描述

相關內容