我怎样才能根据数字的数量级对数字进行四舍五入?

我怎样才能根据数字的数量级对数字进行四舍五入?

这是在答案中提出的一个问题https://tex.stackexchange.com/a/183227/1537

假设我们有一个顺序我们知道它们是某个数量的对数。现在我想计算输入值的指数并以某种很酷的方式格式化结果。我怎样才能避免舍入误差,使其符合全部序列中的数字?

假设问题表述如下

在此处输入图片描述

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fpu}

\begin{document}
\thispagestyle{empty}

% use \newcommand (not \def), so the one (and only)
% argument can be specified in {} (and not in []) brackets
\newcommand{\mynum}[1]{
  % =\pgfmathparse{e^\tick}\pgfmathresult : ! Dimension too large. ; - use exp(x)
  \pgfkeys{/pgf/fpu}% else dimension too large!
  \pgfmathparse{exp(#1)}%
  \pgfmathfloattofixed\pgfmathresult
  \pgfmathresult
}

\message{^^J}

\mynum{-0.69316}

\mynum{0.0}

\mynum{1.60942}

\mynum{2.30258}

\mynum{3.912}

\mynum{4.60516}

\mynum{6.21458}

\mynum{6.90775}

\mynum{8.51717}

\mynum{9.21033}

\mynum{10.81975}

\mynum{11.51291}
\end{document}

理想情况下,每个数字都会四舍五入到相对精度,比如说 3 位数字 - 但相对于数字本身。

答案1

关键是采用/pgf/number format/fixed relative确定相对于当前数字的精度并生成定点数作为结果。

此返回值用于\pgfmathprintnumberto[..., verbatim]强调生成的宏\tmp包含一个标准定点数,即不是格式化(即不包含数学模式的内容,如{,}),并且可以用作其他数字格式化程序的输入。原始问题https://tex.stackexchange.com/a/183227/1537依赖于siunitx。

在此处输入图片描述

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fpu}

\begin{document}
\thispagestyle{empty}

% use \newcommand (not \def), so the one (and only)
% argument can be specified in {} (and not in []) brackets
\newcommand{\mynum}[1]{
  % =\pgfmathparse{e^\tick}\pgfmathresult : ! Dimension too large. ; - use exp(x)
  \pgfkeys{/pgf/fpu}% else dimension too large!
  \pgfmathparse{exp(#1)}%
  \pgfmathfloattofixed\pgfmathresult
  \message{exp(#1) = \pgfmathresult^^J}%
  \pgfmathprintnumberto[
    % it is rounded relative to its (individual!) order of
    % magnitude:
    fixed relative,
    % ... and with three digits relative to its order of
    % magnitude. This should avoid rounding problems
    % since it is applied to each tick number
    % individually.
    precision=3,
    verbatim,
  ]{\pgfmathresult}{\tmp}%
  \message{fixed realtive=\tmp^^J}%
  \tmp
}

\message{^^J}

\mynum{-0.69316}

\mynum{0.0}

\mynum{1.60942}

\mynum{2.30258}

\mynum{3.912}

\mynum{4.60516}

\mynum{6.21458}

\mynum{6.90775}

\mynum{8.51717}

\mynum{9.21033}

\mynum{10.81975}

\mynum{11.51291}
\end{document}

控制台输出是

exp(-0.69316) = 0.50012
fixed realtive=0.5
exp(0.0) = 1.0000000000
fixed realtive=1
exp(1.60942) = 4.99974000000000
fixed realtive=5
exp(2.30258) = 10.000000000
fixed realtive=10
exp(3.912) = 49.9974000000000
fixed realtive=50
exp(4.60516) = 100.00000000
fixed realtive=100
exp(6.21458) = 499.974000000000
fixed realtive=500
exp(6.90775) = 1000.0000000
fixed realtive=1000
exp(8.51717) = 4999.74000000000
fixed realtive=5000
exp(9.21033) = 10000.000000
fixed realtive=10000
exp(10.81975) = 49997.4000000000
fixed realtive=50000
exp(11.51291) = 100000.00000
fixed realtive=100000

相关内容