bc
doesn't like numbers expressed in scientific notation (aka exponential notation).
$ echo "3.1e1*2" | bc -l
(standard_in) 1: parse error
but I need to use it to handle a few records that are expressed in this notation. Is there a way to get bc
to understand exponential notation? If not, what can I do to translate them into a format that bc
will understand?
Let me try to summarize the existing answers, with comments on each below:
(a) If you indeed need to use
bc
for arbitrary-precision calculations - as the OP does - use the OP's own clever approach, which textually reformats the scientific notation to an equivalent expression thatbc
understands.If potentially losing precision is not a concern,
awk
orperl
asbc
alternatives; both natively understand scientific notation, as demonstrated in jwpat7's answer for awk.printf '%.<precision>f'
to simply textually convert to regular floating point representation (decimal fractions, without thee
/E
) (a solution proposed in a since-deleted post by ormaaj).(a) Reformatting scientific notation to an equivalent
bc
expressionThe advantage of this solution is that precision is preserved: the textual representation is transformed into an equivalent textual representation that
bc
can understand, andbc
itself is capable of arbitrary-precision calculations.See the OP's own answer, whose updated form is now capable of transforming an entire expression containing multiple numbers in exponential notation into an equivalent
bc
expression.(b) Using
awk
orperl
instead ofbc
as the calculatorNote: The following approaches assume use of the built-in support for double-precision floating-point values in
awk
andperl
. As is in inherent in floating-point arithmetic,"given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation." (http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html)
That said,
GNU awk offers the option to be built with support for arbitrary-precision arithmetic - see https://www.gnu.org/software/gawk/manual/html_node/Gawk-and-MPFR.html; however, distributions may or may not include that support - verify support by checking the output from
gawk --version
forGNU MPFR
andGNU MP
.If support is available, you must activate it with
-M
(--bignum
) in a given invocation.Perl offers optional arbitrary-precision decimal support via the
Math::BigFloat
package - see https://metacpan.org/pod/Math::BigFloatawk
awk
natively understands decimal exponential (scientific) notation.(You should generally only use decimal representation, because
awk
implementations differ with respect to whether they support number literals with other bases.)If you use the default
print
function, theOFMT
variable controls the output format by way of aprintf
format string; the (POSIX-mandated) default is%.6g
, meaning 6 significant digits, which notably includes the digits in the integer part.Note that if the number in scientific notation is supplied as input (as opposed to a literal part of the awk program), you must add
+0
to force it to the default output format, if used by itself withprint
:Depending on your locale and the
awk
implementation you use, you may have to replace the decimal point (.
) with the locale-appropriate radix character, such as,
in a German locale; applies to BSDawk
,mawk
, and to GNUawk
with the--posix
option.Modifying variable
OFMT
changes the default output format (for numbers with fractional parts; (effective) integers are always output as such).Alternatively, use the
printf
function with an explicit output format:Perl
perl
too natively understands decimal exponential (scientific) notation.Note: Perl, unlike awk, isn't available on all POSIX-like platforms by default; furthermore, it's not as lightweight as awk.
However, it offers more features than awk, such as natively understanding hexadecimal and octal integers.
I'm unclear on what Perl's default output format is, but it appears to be
%.15g
. As with awk, you can useprintf
to choose the desired output format:(c) Using
printf
to convert scientific notation to decimal fractionsIf you simply want to convert scientific notation (e.g.,
1.2e-2
) into a decimal fraction (e.g.,0.012
),printf '%f'
can do that for you. Note that you'll convert one textual representation into another via floating-point arithmetic, which is subject to the same rounding errors as theawk
andperl
approaches.try this (found this in an example for a CFD input data for processing with m4:)
Unfortunately, bc doesn't support scientific notation.
However, it can be translated into a format that bc can handle, using extended regex as per POSIX in sed:
you can replace the "e" (or "e+", if the exponent is positive) with "*10^", which bc will promptly understand. This works even if the exponent is negative or if the number is subsequently multiplied by another power, and allows keeping track of significant digits.
If you need to stick to basic regex (BRE), then this should be used:
From Comments:
A simple bash pattern match could not work (thanks @mklement0) as there is no way to match a e+ and keep the - from a e- at the same time.
A correctly working perl solution (thanks @mklement0)
Thanks to @jwpat7 and @Paul Tomblin for clarifying aspects of sed's syntax, as well as @isaac and @mklement0 for improving the answer.
Edit:
The answer changed quite a bit over the years. The answer above is the latest iteration as of 17th May 2018. Previous attempts reported here were a solution in pure bash (by @ormaaj) and one in sed (by @me), that fail in at least some cases. I'll keep them here just to make sense of the comments, which contain much nicer explanations of the intricacies of all this than this answer does.
You can also define a bash function which calls awk (a good name would be the equal sign "="):
Then you can use all type of floating point math in the shell. Note that square brackets are used here instead of round brackets, since the latter would have to be protected from the bash by quotes.
Or in a script to assign the result
Luckily there is printf, which does the formatting job:
The above example:
Or a float comparison:
I managed to do it with a little hack. You can do something like this -