开发者

How do I stop bc from splitting lines?

I'm using bc from a bash script to do some quick and dirty BigInteger math but, when I bump up the scale, it starts splitting lines on me:

pax> echo 'scale=200 ; 1 / 4' | bc
.2500000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000

pax> num="$(echo 'scale=200 ; 1 / 4' | bc )" ; echo $num
.2500000000000000000000000000000000000000000000000000000000000000000\ 00000 ...

How do I stop this from happening so that I can just get the number without any splits? The man page documents this behaviour but doesn't seem to give any options for changing it.


Actually, I'll step back and tell you the source of the request in case anyone has a better solution. I need an array of strings in C equivalent to the values 2-n, along the lines of:

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)
};
开发者_如何学运维

I don't care what language generates the array, I'm just going to take the output and plug it into my C code. I do need the accuracy however.


At least on my system, the BC_LINE_LENGTH environment variable controls how long the output lines are:

$ 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))

That's the raw values.

If you want to create proper C syntax, use something like this.

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 "};"

That might do what you want.


% echo 'scale=200; 1/4' | bc | tr -d '\n' | tr -d '\\'
.25000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜