题
我正在使用 bc
从bash脚本进行一些快速而肮脏的biginteger数学,但是当我碰到秤时,它开始对我分开线:
pax> echo 'scale=200 ; 1 / 4' | bc
.2500000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000
pax> num="$(echo 'scale=200 ; 1 / 4' | bc )" ; echo $num
.2500000000000000000000000000000000000000000000000000000000000000000\ 00000 ...
如何阻止这种情况发生,以便我可以在没有任何拆分的情况下获得数字? Man Page记录了此行为,但似乎没有提供任何更改它的选择。
实际上,如果有人有更好的解决方案,我将退后一步,告诉您请求的来源。我需要在c中等同于值2的字符串-n, ,沿着:
static char *str[] = {
"1.00000000 ... 000", // 1/1 to 150 fractional places.
"0.50000000 ... 000", // 1/2
"0.25000000 ... 000", // 1/4
"0.12500000 ... 000", // 1/8
: : :
"0.00000000 ... 004", // 1/(2^256)
};
我不在乎哪种语言生成数组,我只需将输出插入我的C代码。但是,我确实需要准确性。
解决方案
至少在我的系统上,bc_line_length环境变量控制输出线的时间:
$ echo 'scale=200; 1/4' | BC_LINE_LENGTH=9999 bc
.25000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
其他提示
localhost:~ slott$ python -c 'print "{0:.200f}".format( 1./4. )'
0.25000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
localhost:~ slott$ python -c 'import decimal; print 1/decimal.Decimal( 2**256 )'
8.636168555094444625386351863E-78
import decimal
for i in range(256):
print "{0:.150f}".format(1/decimal.Decimal(2**i))
那就是原始值。
如果要创建适当的C语法,请使用类似的内容。
def long_string_iter():
for i in range(256):
yield i, "{0:.150f}".format(1/decimal.Decimal(2**i))
def c_syntax( string_iter ):
print "static char *str[] = {"
for i, value in string_iter():
print ' "{0}", // 1/{1}'.format( value, i )
print "};"
那可能会做你想要的。
% echo 'scale=200; 1/4' | bc | tr -d '\n' | tr -d '\\'
.25000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
不隶属于 StackOverflow