BC—automatic full precision multiplication

bccalculator

High, I need to test my arbitrary precision calculator, and bc seems like a nice yardstick to compare to, however, bc does truncate the result of each multiplication to what seems to be the maximum scale of the involved operands each.

Is there a quick way to turn this off or to automatically set the scale of each multiplication to the sum of scales of the factors so that it doesn't lose any precision?

If you have a more elegant solution to this involving something other than bc, I would appreciate your sharing it.

Example:

$ bc <<< '1.5 * 1.5'
2.2

The real answer is 2.25.

Best Answer

You can control the scale that bc outputs with the scale=<#> argument.

$ echo "scale=10; 5.1234 * 5.5678" | bc
28.52606652

$ echo "scale=5; 5.1234 * 5.5678" | bc
28.52606

Using your example:

$ bc <<< 'scale=2; 1.5 * 1.5'
2.25

You can also use the -l switch (thanks to @manatwork) which will initialize the scale to 20 instead of the default of 0. For example:

$ bc -l <<< '1.5 * 1.5'
2.25

$ bc -l <<< '1.52 * 1.52'
2.3104

You can read more about scale in the bc man page.