So I am trying to use bc
to calculate some logarithms but I also need to use it to calculate the modulus for something. Whilst making my script, I launched bc
to test it.
Without any flags, bc <<< "3%5"
of course returns 3
.
But with bc -l
(loads math library so I can compute logarithms) any calculation of a%b
returns 0
where a
and b
can be any number but 0
.
What's happening?
For what it's worth, when I use
bc -l
, I have the following functions defined:That should give you a proper
MOD
function, while keeping your scale intact. Of course, it won't help if you NEED to use the%
operator for some reason.(That
TRUNC
function is quite handy too, forming the basis for many other useful functions that are outside the scope of this answer.)man bc :
So maybe you should set the scale to 0 :
That's because, from the manual:
When you run
bc
with the-l
flag,scale
is set to20
. To fix this:We first save
scale
in variableoldscale
, then setscale
to0
to perform some arithmetic operations, and to compute aln
we setscale
back to its old value. This will output:as wanted.
You could define a function that works in math mode by temporarily setting
scale
to zero.I have
bc
aliased like this:Thus
~/.bcrc
is evaluated before any other expressions, so you can define functions in~/.bcrc
. For example a modulus function:Now you can do modulo like this:
Output:
According to the
bc
manual,So what happens is that it tries to evaluate
a-(a/b)*b
using the currentscale
settings. The defaultscale
is 0 so you get the remainder. When you runbc -l
you getscale=20
and the expressiona-(a/b)*b
evaluates to zero when using 20 fractional digits.To see how it works, try some other fractions:
To make a long story short, just compare three outputs:
Default
scale
with-l
enabled (20):Let's set
scale
to 1:Or to zero (default without
-l
):