我有一个 MWE,我想计算总和和相关误差,在函数 serieF 中实现。如何在函数中实现返回两个输出,即变量 \s 和 \e,然后调用这些变量?
观察:我需要使用 tikzmath。
\documentclass[varwidth,border=5]{article}
\usepackage{tikz}
\usepackage{amsmath}
\usepackage{xfp}
\usetikzlibrary{math}
\usepackage{etoolbox}
\usepackage{fp}
\usetikzlibrary{fixedpointarithmetic}
\usetikzlibrary{calc,fpu}
\usepackage{pgf}
\tikzset{fixed point arithmetic}
\tikzmath{
function serieF(\n) {
real \s; real \a; real \e;
\s = 0;
\e = 0;
for \i in {1,...,\n}{
if isodd(\i+1) == 1 then {
\s = \s - 1/(2*\i-1); %
};
if isodd(\i+1) == 0 then {
\s = \s + 1/(2*\i-1); %
};
\e = abs(1/(2*\i-1));
};
return \s;
};
real \s \e;
\s = serieF(100);
}%
\begin{document}
The approximation for the serie is \s~ with an error of
\end{document}
答案1
可能有更好的方法来使函数的内部变量成为全局变量,但是这个方法可行:
\documentclass{article}
\usepackage{tikz}
\usepackage{amsmath}
\usepackage{xfp}
\usetikzlibrary{math}
\usepackage{etoolbox}
\usepackage{fp}
\usetikzlibrary{fixedpointarithmetic}
\usetikzlibrary{calc,fpu}
\usepackage{pgf}
\tikzset{fixed point arithmetic}
\tikzmath{
function serieF(\n) {
real \s; real \a; real \e;
\s = 0;
\e = 0;
for \i in {1,...,\n}{
if isodd(\i+1) == 1 then {
\s = \s - 1/(2*\i-1); %
};
if isodd(\i+1) == 0 then {
\s = \s + 1/(2*\i-1); %
};
\e = abs(1/(2*\i-1));
};
print {\xdef\mysum{\s}\xdef\myerr{\e}};%
};
}%
\begin{document}
\tikzmath{serieF(100);}
The approximation for the serie
is~\mysum{} with an error of~\myerr.
\end{document}