bc
is absolutely a great tool for this job. It is automatically arbitrary precision and the gotchas with floating point are avoided.
There are a couple of alternates to bc
to consider.
You can use GNU awk if it was compiled with the MPFR library. You need to set the precision to something more than the default 53 bits. In this case, quad precision or 128 bits is fine:
n1="1581097198.000749862"
n2="1581097198.000449861"
gawk -M -v PREC='quad' -v n1="$n1" -v n2="$n2" 'BEGIN{printf ("%.10f\n",n1-n2)}'
0.0003000010
The advantage with gawk
is it is likely faster with a fixed word size floating point vs most arbitrary precision methods. They can be orders of magnitude slower.
You can also use perl
with bignum
:
echo "$n1 $n2" | perl -Mbignum -lanE 'say $F[0]+0.0 - $F[1]'
0.000300001
(The $F[0]+0.0
just tells Perl to treat $F[0]
as number which then triggers the conversion to a bignum)