[20170622]bc与取模运算.txt
--//前一阵子在使用bc做取模运算.发现一个奇怪的问题.开始以为是使用mod(受oracle的影响).
--//查手册才发现%.
--//例子如下:
$ bc -v
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
$ bc -q
9%4
1
9%5
4
--//很明显以上结果是正确的,但是如果加参数-l.
-l, --mathlib => Define the standard math library.
$ bc -lq
9%4
0
9%5
0
scale=12
9%5
0
9%4
0
--//很明显这个时候就不对了.
$ bc -lq
12312324%1232
.00000000000000001168
$ bc -q
12312324%1232
948
--//为什么呢?也就是如果使用-l参数,使用standard math library. %不再是取模运算.到底做什么运算呢?
$ man bc
--//里面一段话如下:
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
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
1/3
.33333333333333333333
--//可以看出使用math 库,缺省scale=20.
--//而如果不使用-l参数scale=0.
--//这样如果在scale=20的情况,取模使用是这样.
12312324/1232
9993.76948051948051948051
12312324-9993.76948051948051948051*1232
.00000000000000001168
scale=2
12312324%1232
11.68
12312324/1232
9993.76
--//bc竟然没做四舍五入.
12312324-9993.76*1232
11.68