Float operation with bc?

bc doesn't do floating point but it does do fixed precision decimal numbers. The -l flag Hauke mentions loads a math library for eg. trig functions but it also means

[...] the default scale is 20

scale is one of a number of "special variables" mentioned in the man page. You can set it:

scale=4

Anytime you want (whether -l was used or not). It refers to the number of significant digits used in a decimal. In other words, subsequent solutions will be rounded to that number of digits after the decimal scale (== fixed precision).

The default scale sans -l is 0, meaning rounded to whole numbers.


man page says:

If bc is invoked with the -l option, a math library is preloaded [...]

The comprehensibility of that could be improved, indeed...


when I do echo 1/8 | bc it get me a zero.

Yes, by default, the value of scale (the count of decimals) is zero (0), in that case, bc still do arbitrary precision math but with no numbers after the dot.

$ echo 234^34 | bc
35755195084527581333820034812187200823956346053610939764649481375776\
5274080116736

That is: integer arbitrary precision math.

By changing the value of the variable scale the number of decimals could be changed:

$ echo 'scale=3; 1/8' | bc 
.125

$ echo 'scale=27; 1/8' | bc 
.125000000000000000000000000

It looks like bc doesn't support float operations

No, bc has no notion of a float (as defined in IEEE-754 at least).

What bc does is arbitrary precision math on decimal fractions (finite number of decimals, of digits after the decimal separator).

The number of digits after the decimal separator is set by the variable scale.

$ echo 'scale=5; sqrt(2)' | bc
1.41421

$ echo 'scale=35; sqrt(2)' | bc
1.41421356237309504880168872420969807

The function sqrt is basic and part of the default bc.
Some other functions (log, sen, cos, atan, etc) could be loaded with bc -l

   s (x)    The sine of x, x is in radians.
   c (x)    The cosine of x, x is in radians.
   a (x)    The arctangent of x, arctangent returns radians.
   l (x)    The natural logarithm of x.
   e (x)    The exponential function of raising e to the value x.
   j (n,x)  The Bessel function of integer order n of x.

Which also sets the scale to 20 (could be changed after started).

So:

$ echo '1/8' | /bin/bc -l
.12500000000000000000

Tags:

Bc