Why does Unix give the result 0 when I execute the following command?
echo "7%2" | bc -l
And give result 1 when I execute the following command?
echo "7%2" | bc
Why does Unix give the result 0 when I execute the following command?
echo "7%2" | bc -l
And give result 1 when I execute the following command?
echo "7%2" | bc
why does Unix gives result 0 when I execute the command: echo "7%2" | bc -l
From the bc
manual:
If bc is invoked with the -l option, a math library is preloaded and the default scale is set to 20.
And
expr % expr
The result of the expression is the "remainder" and it is computed in the following way. To compute a%b, first a/b is computed to scale digits. That result is used to compute a-(a/b)*b to the scale of the maximum of scale+scale(b) and scale(a). If scale is set to zero and both expressions are integers this expression is the integer remainder function.
So:
a=7 b=2
a/b = 7 / 2 = 3.50000000000000000000000000000000000000000000000000
7%2 = a-(a/b)*b =
= 7 - (7/2)*2 =
= 7 - (3.50000000000000000000000000000000000000000000000000) * 2 =
= 7 - 7 =
= 0
and gives result 1 when I execute the command: echo "7%2" | bc
From the bc
manual:
scale defines how some operations use digits after the decimal point. The default value of scale is 0.
In that case:
a=7 b=2
a/b = 7 / 2 = 3 # scale is 0, rounds down
a%b = a-(a/b)*b =
= 7 - (7/2)*2 =
= 7 - 3 * 2 =
= 7 - 6 =
= 1
Because the 7/2
is computed with different scale, the resulting expression differs.