簡體   English   中英

bash,bc模不適用於-l標志

[英]bash, bc modulo does not work with -l flag

因此,我嘗試使用bc來計算一些對數,但我還需要使用它來計算某些事物的模數。 在編寫腳本的同時,我啟動了bc進行測試。

沒有任何標志, bc <<< "3%5"當然會返回3

但是,使用bc -l (加載數學庫,以便我可以計算對數)時, a%b任何計算都a%b返回0 ,其中ab可以是除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 要解決此問題:

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.

因此,發生的事情是它將嘗試使用當前的scale設置來評估a-(a/b)*b 默認的scale為0,因此可以得到余數。 運行bc -l會得到scale=20 ,當使用20個小數位時,表達式a-(a/b)*b值為零。

要查看其工作原理,請嘗試其他一些步驟:

$ bc -l
1%3
.00000000000000000001

簡而言之,只需比較三個輸出:

啟用-l默認scale (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

男子卑詩省:

如果使用-l選項調用bc,則會預先加載數學庫,並且默認比例設置為20。

因此,也許您應該將小數位設置為0:

#bc
scale=0
10%3
1

值得的是,當我使用bc -l ,我定義了以下函數:

define trunc(x)   {auto s; s=scale; scale=0; x=x/1; scale=s; return x}
define mod(x,y)   {return x-(y*trunc(x/y))}

這應該為您提供適當的MOD功能,同時保持秤完整無缺。 當然,如果由於某種原因需要使用%運算符,這將無濟於事。

TRUNC函數也很方便,它構成了此答案范圍之外的許多其他有用函數的基礎。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM