所以我试图用来bc计算一些对数但我还需要用它来计算某些东西的模数.在制作我的剧本时,我开始bc测试它.
没有任何标志,bc <<< "3%5"当然会返回3.
但是bc -l(加载数学库,所以我可以计算对数)任何a%b返回的计算,0其中a和b可以是任何数字但0.
发生了什么?
gni*_*urf 13
那是因为,从手册:
   expr % expr
          The result of the expression is the "remainder" and it  is  com?
          puted  in  the following way.  To compute a%b, first a/b is com?
          puted 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.
bc使用-l标志运行时,scale设置为20.解决这个问题:
bc -l <<< "oldscale=scale; scale=0; 3%5; scale=oldscale; l(2)"
我们首先保存scale变量oldscale,然后设置scale为0执行一些算术运算,并计算ln我们设置scale回旧值.这将输出:
3
.69314718055994530941
如所想.
根据bc手册,
   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.
所以会发生的是它尝试a-(a/b)*b使用当前scale设置进行评估.默认scale值为0,因此您可以获得余数.当你运行bc -lget get 时,当使用20个小数位时scale=20,表达式的a-(a/b)*b计算结果为零.
要了解它是如何工作的,请尝试其他一些分数:
$ bc -l
1%3
.00000000000000000001
简而言之,只需比较三个输出:
默认scale以-l启用(20):
scale
20
3%5
0
1%4
0
我们设置scale为1:
scale=1
3%5
0
1%4
.2
或者为零(默认为不-l):
scale=0
3%5
3
1%4
1
您可以通过临时设置scale为零来定义在数学模式下工作的函数.
我有这样的bc别名:
alias bc='bc -l ~/.bcrc'
因此~/.bcrc在任何其他表达式之前进行评估,因此您可以在其中定义函数~/.bcrc.例如模数函数:
define mod(x,y) { 
  tmp   = scale
  scale = 0
  ret   = x%y
  scale = tmp
  return ret
}
现在你可以这样做模数:
echo 'mod(5,2)' | bc
输出:
1