-1

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jmandy
  • 1
  • 1
  • See [man 1 bc](https://linux.die.net/man/1/bc) under the "MATH LIBRARY" heading. There are some functions that require the library, and additionally it effects the `scale` defaulting to 20. Modulo does not. – David C. Rankin Sep 12 '20 at 12:40
  • I edited the tags. This is purely about `bc`, not `unix` or `bash` as previously tagged. – chepner Sep 12 '20 at 13:10

1 Answers1

1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
KamilCuk
  • 120,984
  • 8
  • 59
  • 111