
Мне нужно построить несколько графиков. Первый — график функции
\begin{equation}
x(t)= -e^{ -(0.1 \ {s}^{-1}) t} \cos \left( ( 0.995 \ {rad} / \mathrm{s})t \right)
\end{equation}
и $\dot{x}$ (функция производной по времени)
\begin{equation}
\dot{x}(t)= e^{-(0.1 \ {s}^{-1}) t}\left[(0.1 \ {s}^{-1}) \cos \left( ( 0.995 \ {rad} / \mathrm{s})t \right)+ ( 0.995 \ {rad} / \mathrm{s})\sin ( ( 0.995 \ {rad} / \mathrm{s})t )\right] .
\end{equation}
До сих пор я делал их индивидуальные графики следующим образом:
\begin{figure}[ht]
\centering
\caption{ The plots of the position and speed versus time (underdamped oscillator).}
\begin{tikzpicture}[scale=1.9]
\begin{axis}[
axis lines = left,
xlabel = {$t$, $ \left[\text{s} \right]$},
%ylabel = {$a(t)$, $ \left[\text{m/s}^2 \right]$},
grid=major,
ymin=-1,
ymax=1,
]
\addplot [
domain=0:60,
samples=300,
color=YellowGreen,
thick,
]
{2.71828^(-0.1*x)*cos(deg(0.995*x-3.1415))};
\addlegendentry{\tiny $ x(t)$, , $ \left[\text{cm} \right]$}
\addplot [
domain=0:60,
samples=300,
color=TealBlue,
thick,
]
{-2.71828^(-0.1*x)*((0.1*cos(deg(0.995*x-3.1415))+0.995*sin(deg(0.995*x-3.1415))) };
\addlegendentry{\tiny $ \dot{x}(t)$, $ \left[\text{cm/s} \right]$}
\end{axis}
\end{tikzpicture}
\end{figure}
с полученным графиком
Что остается проблемой: вопрос 1.Второй график, который мне нужен, это фазовая диаграмма, т. е. график $\dot{x}(t)$ против $x(t)$, который я не уверен, как построить. Я думал, что выборка/сбор точек функции $x(t)$ и $\dot{x}(t)$, чтобы затем использовать эти точки для интерполяции-построения фазовой диаграммы, может быть как-то реализована? Однако я не смог найти много информации о таких вещах на форумах latex. Мой парень сделал свои графики с помощью python, поэтому я знаю, что фазовая диаграмма должна выглядеть следующим образом
Но я надеялся, что есть какой-то способ сделать графики, используя только латекс. Есть идеи?
Что остается проблемой: вопрос 2.Мне также было интересно, есть ли способ определить, сколько раз система пересекает линию $x=0$, прежде чем амплитуда упадет ниже $10^{-2}$ от своего максимального значения, но возможно ли это сделать только с помощью команд latex для вывода этого числа.
решение1
Видимо, у нас с Bamboo были очень похожие идеи. В этом также учитываются пересечения, о которых вы спрашиваете во второй части вопроса. (Было много уборки, многие изменения очень похожи на хороший ответ Bamboo.)
\documentclass{article}
\usepackage{geometry}
\usepackage[fleqn]{amsmath}
\usepackage{siunitx}
\usepackage[dvipsnames]{xcolor}
\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}% loads intersections
\pgfplotsset{compat=1.17}
\begin{document}
\begin{equation}
x(t)= -\mathrm{e}^{ -(\SI{0.1}{\per\second}) t}\,
\cos \left( ( \SI{0.995}{\radian\per\second})t \right)
\end{equation}
and of $\dot{x}$ (time derivative function)
\begin{equation}
\dot{x}(t)= \mathrm{e}^{-(\SI{0.1}{\per\second}) t}
\left[(\SI{0.1}{\per\second}) \cos \left( (\SI{0.995}{\radian\per\second})t \right)
+ ( \SI{0.995}{\radian\per\second})\sin ( ( \SI{0.995}{\radian\per\second})t )\right] .
\end{equation}
\begin{figure}[ht]
\centering
\caption{The plots of the position and speed versus time (underdamped oscillator).}
\begin{tikzpicture}[scale=1.6]
\begin{axis}[declare function={%
pos(\x)=exp(-0.1*\x)*cos(deg(0.995*\x-pi));%
posdot(\x)=-exp(-0.1*\x)*((0.1*cos(deg(0.995*\x-pi))+0.995*sin(deg(0.995*\x-pi)));
},
axis lines = left,
xlabel = {$t$, $ \left[\text{s} \right]$},
%ylabel = {$a(t)$, $ \left[\text{m/s}^2 \right]$},
grid=major,
ymin=-1,
ymax=1,
legend style={font=\footnotesize}
]
\addplot [
domain=0:60,
samples=300,
color=YellowGreen,
thick,
]
{pos(x)};
\addlegendentry{$ x(t)~\left[\si{\centi\meter}\right]$}
\addplot [
domain=0:60,
samples=300,
color=TealBlue,
thick,
]
{posdot(x)};
\addlegendentry{$\dot{x}(t)~ \left[\si{\centi\meter\per\second} \right]$}
\end{axis}
\end{tikzpicture}
\end{figure}
\begin{figure}[ht]
\centering
\begin{tikzpicture}[scale=1.6]
\begin{axis}[declare function={%
pos(\x)=exp(-0.1*\x)*cos(deg(0.995*\x-pi));%
posdot(\x)=-exp(-0.1*\x)*((0.1*cos(deg(0.995*\x-pi))+0.995*sin(deg(0.995*\x-pi)));
},
axis lines = left,
xlabel = {$x(t)~ \left[\si{\centi\meter} \right]$},
ylabel = {$\dot x(t)~ \left[\si{\centi\meter\per\second} \right]$},
grid=major,
ymin=-1,
ymax=1,
xmax=0.75
]
\addplot [
domain=0:60,
samples=601,
color=blue,
thick,smooth
]({pos(x)},{posdot(x)});
\addplot [name path=phase,
domain=0:60,
samples=601,
draw=none]({pos(x)},{posdot(x)});
\path[name path=axis]
(0,1) -- (0,{abs(pos(0))/100})
(0,-1) -- (0,{-abs(pos(0))/100})
;
\path[name intersections={of=phase and axis,total=\t}]
\pgfextra{\xdef\MyNumIntersections{\t}};
\end{axis}
\end{tikzpicture}
\caption{Phase space diagram. The phase curve intersects
$\MyNumIntersections$
times with the $x=0$ axis before reaching 0.01 times its maximal value.}
\end{figure}
\end{document}
Примечание:
- Я оставил декларацию функций локальной, поскольку ее несколько сложнее переобъявить, хотя и не невозможно. То есть, если вы объявляете
pos(\x)
глобально, вы не сможете легко объявить другую функцию с этим именем. - pgf знает значения
pi
иe
, и вы можете использовать этуexp
функцию. - Я вычисляю пересечение с помощью невидимого, негладкого графика, поскольку число пересечений никогда не бывает полностью достоверным и становится более шатким для гладких графиков.
ПРИЛОЖЕНИЕ: Просто ради забавы: здесь используется хорошая идея Bamboo по установке фильтра для вычисления пересечений впервыйplot, где результат гораздо надежнее. Хорошей новостью является то, что число 14 подтверждается, так что вышеприведенное, похоже, дает правильное число (случайно или нет). Аналитический результат — int(10*ln(100))=14
, так что все хорошо. В этой версии я также удалил \left
и \right
s, как предложил Bamboo. В любом случае, суть в том, что вычисление пересечений на первом графике должно быть очень надежным, во втором графике я не так уверен.
\documentclass{article}
\usepackage{geometry}
\usepackage[fleqn]{amsmath}
\usepackage{siunitx}
\usepackage[dvipsnames]{xcolor}
\usepackage{pgfplots}
\usepgfplotslibrary{fillbetween}% loads intersections
\pgfplotsset{compat=1.17}
\begin{document}
\begin{equation}
x(t)= -\mathrm{e}^{ -(\SI{0.1}{\per\second}) t}\,
\cos \left( ( \SI{0.995}{\radian\per\second})t \right)
\end{equation}
and of $\dot{x}$ (time derivative function)
\begin{equation}
\dot{x}(t)= \mathrm{e}^{-(\SI{0.1}{\per\second}) t}
\left[(\SI{0.1}{\per\second}) \cos \left( (\SI{0.995}{\radian\per\second})t \right)
+ ( \SI{0.995}{\radian\per\second})\sin ( ( \SI{0.995}{\radian\per\second})t )\right] .
\end{equation}
\begin{figure}[ht]
\centering
\caption{The plots of the position and speed versus time (underdamped oscillator).}
\begin{tikzpicture}[scale=1.6]
\begin{axis}[declare function={%
pos(\x)=exp(-0.1*\x)*cos(deg(0.995*\x-pi));%
posdot(\x)=-exp(-0.1*\x)*((0.1*cos(deg(0.995*\x-pi))+0.995*sin(deg(0.995*\x-pi)));
},
axis lines = left,
xlabel = {$t~ [\text{s} ]$},
%ylabel = {$a(t)$, $ \left[\text{m/s}^2 \right]$},
grid=major,
ymin=-1,
ymax=1,
legend style={font=\footnotesize}
]
\addplot [
domain=0:60,
samples=300,
color=YellowGreen,
thick,
]
{pos(x)};
\addlegendentry{$ x(t)~[\si{\centi\meter}]$}
\addplot [
domain=0:60,
samples=300,
color=TealBlue,
thick,
]
{posdot(x)};
\addlegendentry{$\dot{x}(t)~ [\si{\centi\meter\per\second} ]$}
\addplot [name path=x,
x filter/.expression={abs(pos(x))<abs(pos(0))/100 ? nan :x},
domain=0:60,
samples=300,
draw=none]
{pos(x)};
\path[name path=axis] (0,0) -- (60,0);
\path[name intersections={of=x and axis,total=\t}]
foreach \X in {1,...,\t} {(intersection-\X) node[red,circle,inner sep=1.2pt,fill]{}}
(60,-1) node[above left,font=\footnotesize,
align=right,text width=6.5cm]{$x(t)$ intersects $\t$ times
with the $x=0$ axis before dropping below $1\%$ of its initial amplitude.};
\end{axis}
\end{tikzpicture}
\end{figure}
\begin{figure}[ht]
\centering
\begin{tikzpicture}[scale=1.6]
\begin{axis}[declare function={%
pos(\x)=exp(-0.1*\x)*cos(deg(0.995*\x-pi));%
posdot(\x)=-exp(-0.1*\x)*((0.1*cos(deg(0.995*\x-pi))+0.995*sin(deg(0.995*\x-pi)));
},
axis lines = left,
xlabel = {$x(t)~ [\si{\centi\meter}]$},
ylabel = {$\dot x(t)~ [\si{\centi\meter\per\second} ]$},
grid=major,
ymin=-1,
ymax=1,
xmax=0.75
]
\addplot [
domain=0:60,
samples=601,
color=blue,
thick,smooth
]({pos(x)},{posdot(x)});
\addplot [name path=phase,
domain=0:60,
samples=601,
draw=none]({pos(x)},{posdot(x)});
\path[name path=axis]
(0,1) -- (0,{abs(pos(0))/100})
(0,-1) -- (0,{-abs(pos(0))/100})
;
\path[name intersections={of=phase and axis,total=\t}]
\pgfextra{\xdef\MyNumIntersections{\t}};
\end{axis}
\end{tikzpicture}
\caption{Phase space diagram. The phase curve intersects
$\MyNumIntersections$
times with the $x=0$ axis before reaching 0.01 times its maximal value.}
\end{figure}
\end{document}
решение2
Вот несколько более чистая версия вашего кода вместе с параметрическим графиком, упомянутым котом @Schrödinger.
Обратите внимание на использование пакета siunitx
для набора единиц. Кроме того, \left[... \right]
они действительно не нужны в такой ситуации. Наконец, я явно объявил ваши функции, чтобы облегчить их использование с настройкой tikz
declare function
.
РЕДАКТИРОВАТЬОбновленная версия, отображающая пересечения и рисующая узел на параметрическом графике с использованием этой информации. Обратите внимание, что я использую a x filter
для отбрасывания результатов с низкой амплитудой на этом графике, что заметно отличается от подхода с котом Шредингера.
\documentclass[tikz,dvipsnames,border=3.14mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\usepackage{siunitx}
\usetikzlibrary{intersections}
\tikzset{
declare function={
f(\t) = 2.71828^(-0.1*\t)*cos(deg(0.995*\t-3.1415));
df(\t) = -2.71828^(-0.1*x)*((0.1*cos(deg(0.995*x-3.1415))+0.995*sin(deg(0.995*x-3.1415)));
},
}
\begin{document}
\begin{tikzpicture}[scale=1.9]
\begin{axis}[
axis lines = left,
xlabel = {$t \quad [\si{\second}]$},
grid=major,
ymin=-1,
ymax=1,
legend cell align=left,
legend style={font=\small},
domain=0:60,
samples=300,
]
\addplot [color=YellowGreen,thick] {2.71828^(-0.1*x)*cos(deg(0.995*x-3.1415))};
\addlegendentry{$x(t) \quad [\si{\centi\meter}]$}
\addplot [color=TealBlue,thick] {-2.71828^(-0.1*x)*((0.1*cos(deg(0.995*x-3.1415))+0.995*sin(deg(0.995*x-3.1415)))};
\addlegendentry{$\dot{x}(t) \quad [\si{\meter\per\second}]$}
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}[scale=1.9]
\begin{axis}[
axis lines = left,
xlabel = {$x(t) \quad [\si{\centi\meter}]$},
ylabel = {$\dot{x}(t) \quad [\si{\centi\meter\per\second}]$},
grid=major,
ymin=-1,
ymax=1,
legend cell align=left,
legend style={font=\small},
domain=0:60,
samples=300,
x filter/.expression={abs(x)>1e-2 ? x : nan)},
clip=false,
]
\addplot [color=YellowGreen,thick, name path=paramplot] ({f(x)},{df(x)});
\path[name path=yzeroline] (\pgfkeysvalueof{/pgfplots/xmin},0) -- (\pgfkeysvalueof{/pgfplots/xmax},0);
\path[name intersections={of=paramplot and yzeroline,total=\totalintersects}]
foreach \nb in {1,...,\totalintersects}{
node[circle,fill=red, inner sep=1pt] at (intersection-\nb){}
}
node[draw,fill=white,anchor=south west,outer sep=0pt] at (rel axis cs:0.01,0.01) {Number of intersections : \totalintersects}
;
\end{axis}
\end{tikzpicture}
\end{document}