So I am trying to do some a bit involved computations with LaTeX, and it kept spitting out a nonsense answer. I am trying to compute number of layers you could cover a ball with, given some conditions, and LaTeX keeps giving me a negative answer! After pulling out my hair for hours, I was able to track down the error, which is shown in the MWE below
\documentclass[border=1mm]{article}
\usepackage[utf8]{inputenc}
\usepackage{mathtools}
\usepackage{pgfplots}
\begin{document}
\pgfmathsetmacro{\earthRadiusKm}{6371}
\pgfmathsetmacro{\coinRadiusM}{1.05 / 1000}
\pgfmathsetmacro{\coinHeightM}{1.7 / 1000}
\pgfkeys{/pgf/fpu, /pgf/fpu/output format=fixed}
\pgfmathsetmacro{\coinsTotalHeight}{3.27*10^17}
\pgfmathsetmacro{\earthRadiusM}{6371*1000}
\pgfmathsetmacro{\radiusCoinsLayerCubedMtest}{%
(\earthRadiusM^3)^(1/3) - \earthRadiusM}
\pgfmathsetmacro{\R}{
((\earthRadiusM)^3 + 1.5 * (\coinRadiusM) * (\coinsTotalHeight))^(1/3)
}
\pgfmathsetmacro{\layers}{
(\R - \earthRadiusM)/(\coinHeightM)
}
\pgfkeys{/pgf/fpu=false}
$\sqrt{(R_\oplus^3)^{1/3} - R_\oplus}$ equals $0$ not \radiusCoinsLayerCubedMtest !
The radius is
\begin{align*}
R = \sqrt[3]{R_\oplus^3 + \frac{3}{2}r_m h_c}
\approx
\R
\end{align*}
%
Which means that the total number of layers are
%
\begin{align*}
n &= \frac{R - R_\oplus}{h_m} \\
&\approx \frac{\R - \earthRadiusM}{\coinHeightM}
\approx \layers
\end{align*}
\end{document}
The problem is that
(something^3)^(1/3) - something
does not equal zero, presumably because of rounding errors.
It is clear that the expression above should evaluate to zero, however it does not. Instead I get -1400.0
which is complete nonsense. How can I get the fpu library too accurately calculate square roots?
My actual example is a little more involved, but it boils down to calculating the same thing.
\directlua{earthRadiusM=6371*1000; tex.sprint((earthRadiusM^(1/3))^3 - earthRadiusM)}
under LuaLaTeX returns-6.5192580223083e-09
. Not exactly equal to zero either, but nevertheless about 12 orders of magnitude closer...