代码之家  ›  专栏  ›  技术社区  ›  paxdiablo

如何阻止BC拆分行?

  •  2
  • paxdiablo  · 技术社区  · 14 年前

    我在用 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 ...
    

    我怎样才能阻止这种情况的发生,这样我就可以得到不需要任何拆分的数字?手册页记录了这种行为,但似乎没有给出任何改变它的选择。


    实际上,我会退一步告诉您请求的来源,以防有人有更好的解决方案。我需要一个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代码中。不过,我确实需要准确度。

    3 回复  |  直到 13 年前
        1
  •  2
  •   Sean    14 年前

    至少在我的系统中,bc_line_length环境变量控制输出行的长度:

    $ echo 'scale=200; 1/4' | BC_LINE_LENGTH=9999 bc
    .25000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    
        2
  •  1
  •   S.Lott    14 年前
    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 "};"
    

    这可能是你想要的。

        3
  •  0
  •   Janus Troelsen    13 年前
    % echo 'scale=200; 1/4' | bc | tr -d '\n' | tr -d '\\'
    .25000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
    
    推荐文章