bash,bc模不适用于-l标志 [英] bash, bc modulo does not work with -l flag

查看:92
本文介绍了bash,bc模不适用于-l标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我尝试使用bc来计算一些对数,但是我还需要使用它来计算某些事物的模数.在编写脚本的同时,我启动了bc对其进行测试.

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.

没有任何标志,bc <<< "3%5"当然会返回3.

Without any flags, bc <<< "3%5" of course returns 3.

但是使用bc -l(加载数学库,以便我可以计算对数),a%b的任何计算都会返回0,其中ab可以是除0之外的任何数字.

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.

发生了什么事?

推荐答案

这是因为,根据手册:

   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.

使用-l标志运行bc时,scale设置为20.要解决此问题:

When you run bc with the -l flag, scale is set to 20. To fix this:

bc -l <<< "oldscale=scale; scale=0; 3%5; scale=oldscale; l(2)"

我们首先将scale保存在变量oldscale中,然后将scale设置为0以执行一些算术运算,并计算ln,我们将scale设置回原来的值.这将输出:

We first save scale in variable oldscale, then set scale to 0 to perform some arithmetic operations, and to compute a ln we set scale back to its old value. This will output:

3
.69314718055994530941

根据需要.

这篇关于bash,bc模不适用于-l标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆