↑↑ Home ↑ UNIX  

Mathematical correctness for Gnu bc

bc is an ancient UNIX command-line calculator that supports arbitrarily large numbers, different bases and (with the -l option) fractional computations and some transcendental functions. However a long-standing bug causes wrong results with fractional numbers in a base other than 10.

The problem is in the input and output of fractional quantities in a general base. You can easily check if your version of bc has these bugs:

bc -l <<EOF

All these equal 11/16, so in the default output base obase=10 and the default precision scale=20 the result should be .6875, possibly with zeros appended. FreeBSD bc gets this right, but Gnu bc outputs 0.6 for the first input and claims a division by zero for the last.

A similar discrepancy exists for output in bases other than 10. The input:

bc -l <<EOF

gives .7 for the first row, and the correct .777777777777777777 for the second. This bug exists in both FreeBSD and Gnu bc.

Here is a patch for Gnu bc that fixes both issues.

As an aside, the maintainer of Gnu bc has replied with standards lawyering when confronted with these bugs. Actually the the relevant part of the POSIX standard prescribes a precision of 10s on output, where s is the "scale of the value being output", which can be interpreted as something other than scale. The standard has nothing to say on input base conversion, which is completely open to even the most braindead interpretation. Even if the standard was clear, this would be a case of bug-for-bug compatibility at best. Common sense (that a calculator should be mathematically accurate or that the POSIX standard may assume mathematical literacy in its readers) is of course an alien concept in IT, which explains why a lot of software is such junk.

TOS / Impressum