今日想用 bc 來計算帶小數點的指數,例如 2^0.33 (為什麼我總要幹這種事?用WINDOWS的計算機按按就好了不是嗎?那不是重點)
好吧,就然遇到問題了,就來解決一下:
$ bc -l <== 加上 -l(L的小寫) 的參數,可是使用內建的幾個函數
scale=20
2.88 ^ 0.55
Runtime warning (func=(main), adr=12): non-zero scale in exponent
1
2.88 ^ 0.55
Runtime warning (func=(main), adr=12): non-zero scale in exponent
1
上面企圖計算 2.88的0.55次方,出現了 Runtime 的警告,同時答案也不對。
因此認真看了一下男人 man bc:
expr ^ expr
The result of the expression is the value of the first raised to the second. The second expression must be an integer. (If the second expression is not an integer, a warning is generated and the expression is truncated to get an integer value.) The scale of the result is scale if the exponent is negative. If the exponent is positive the scale of the result is the minimum of the scale of the first expression times the value of the exponent and the maximum of scale and the scale of the first expression. (e.g. scale(a^b) = min(scale(a)*b, max( scale, scale(a))).) It should be noted that expr^0 will always return the value of 1.
The result of the expression is the value of the first raised to the second. The second expression must be an integer. (If the second expression is not an integer, a warning is generated and the expression is truncated to get an integer value.) The scale of the result is scale if the exponent is negative. If the exponent is positive the scale of the result is the minimum of the scale of the first expression times the value of the exponent and the maximum of scale and the scale of the first expression. (e.g. scale(a^b) = min(scale(a)*b, max( scale, scale(a))).) It should be noted that expr^0 will always return the value of 1.
它說:第二項(指數部分)一定要整數,如果不是整數的話,會無條件捨去小數部分。其他在說精確位數的事。
好吧,竟然不給小數的指數計算,所以只好用別的方法來解決。
假設要計算: a^b
讚!以上例 2.88 ^ 0.55 來算:
只要輸入
e(0.55*l(2.88))
1.78922875125216803973
1.78922875125216803973
感謝 jlinkels 給的數學推導
參考資料
原文 2011-03-20 21:00:17