Hot answers tagged

83

bc is used during the kernel build to generate time constants in header files. You can see it invoked in Kbuild, where it processes kernel/time/timeconst.bc to generate timeconst.h. This could be implemented as a C program which is built and run during the build, but it’s easier to use bc (which is small and common; in fact it’s part of the set of tools ...


76

With GNU datamash: $ printf '%s\n' 1 2 4 | datamash max 1 min 1 mean 1 median 1 4 1 2.3333333333333 2


70

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 ...


65

Once ibase=16 is done, further input numbers are in hexadecimal, including 10 in obase=10 which represents the decimal value 16. So either set obase before, or set it after, using the new input base (now hexadecimal): $ echo 'obase=10; ibase=16; FF' | bc 255 $ echo 'ibase=16; obase=A; FF' | bc 255


43

dc is a very archaic tool and somewhat older than bc. To quote the Wikipedia page: It is one of the oldest Unix utilities, predating even the invention of the C programming language; like other utilities of that vintage, it has a powerful set of features but an extremely terse syntax. The syntax is a reverse polish notation, which basically means that ...


39

What you actually want to say is: $ echo "ibase=16; C0" | bc 192 for hex-to-decimal, and: $ echo "obase=16; 192" | bc C0 for decimal-to-hex. You don't need to give both ibase and obase for any conversion involving decimal numbers, since these settings default to 10. You do need to give both for conversions such as binary-to-hex. In that case, I find it ...


35

man page says: If bc is invoked with the -l option, a math library is preloaded [...] The comprehensibility of that could be improved, indeed...


28

Minimum: jq -s min awk 'NR==1||$0<x{x=$0}END{print x}' Maximum: jq -s max awk 'NR==1||$0>x{x=$0}END{print x}' Median: jq -s 'sort|if length%2==1 then.[length/2|floor]else[.[length/2-1,length/2]]|add/2 end' sort -n|awk '{a[NR]=$0}END{print(NR%2==1)?a[int(NR/2)+1]:(a[NR/2]+a[NR/2+1])/2}' Average: jq -s add/length awk '{x+=$0}END{print x/NR}' Combined ...


25

Python imports a large number of files at startup: % python -c 'import sys; print len(sys.modules)' 39 Each of these requires an even greater number of attempts at opening a Python file, because there are many ways to define a module: % python -vv -c 'pass' # installing zipimport hook import zipimport # builtin # installed zipimport hook # trying site.so ...


20

I achieved this using sed and replacing the end of the line: echo "my text" | sed 's/$/ more text/' Returns: my text more text Your example: echo "750/12.5" | bc | sed 's/$/\/24/' | bc


19

pythonpy works well for this sort of thing: cat file.txt | py --ji -l 'min(l), max(l), numpy.median(l), numpy.mean(l)'


18

If you aren't happy with the command line editing features that are built into a program, you can run it through rlwrap. This is a wrapper around a command line processor (a REPL) that lets you edit each line before it's sent. Rlwrap uses the readline library and saves history separately for each command. Running rlwrap bc won't do anything for you because ...


14

In the GNU implementation of bc, there is the environment variable BC_LINE_LENGTH (cf man bc): ~$ echo "scale=2; 2^500" | bc 32733906078961418700131896968275991522166420460430647894832913680961\ 33796404674554883270092325904157150886684127560071009217256545885393\ 053328527589376 ~$ export BC_LINE_LENGTH=99999 #or better 0 ~$ echo "scale=2; 2^500" | bc ...


14

This answer to the first linked question has the almost-throwaway line at the end: See also %g for rounding to a specified number of significant digits. So you can simply write printf "%.2g" "$n" (but see the section below on decimal separator and locale, and note that non-Bash printf need not support %f and %g). Examples: $ printf "%.2g\n" 76543 0....


14

You need to understand the meaning of the scale of an expression in bc. bc can do arbitrary precision (which doesn't necessarily mean infinite precision) while your calculator will probably have the precision of the float or double data type of your processor. In bc. The scale is the number of decimal after the dot, so related to the precision. The scale of ...


13

You can control the scale that bc outputs with the scale=<#> argument. $ echo "scale=10; 5.1234 * 5.5678" | bc 28.52606652 $ echo "scale=5; 5.1234 * 5.5678" | bc 28.52606 Using your example: $ bc <<< 'scale=2; 1.5 * 1.5' 2.25 You can also use the -l switch (thanks to @manatwork) which will initialize the scale to 20 instead of the default ...


13

This awk seems to do the trick: while IFS= read i; do awk "BEGIN { print ($i) }" done < math.txt From here Note that we're using ($i) instead of $i to avoid problems with arithmetic expressions like 1 > 2 (print 1 > 2 would print 1 into a file called 2, while print (1 > 2) prints 0, the result of that arithmetic expression). Note that ...


12

And this works too: echo '(2.1+2.1)/2' | bc -l Ah, but did you try: echo '(2.1+2.1)/2' | tr -d '\n' | bc -l (standard_in) 1: syntax error Using echo -n will accomplish the same thing -- there's no terminating newline, and that's your problem.


12

echo "scale=2; 2^500" | bc | tr -d '\n\\' Output: 3273390607896141870013189696827599152216642046043064789483291368096133796404674554883270092325904157150886684127560071009217256545885393053328527589376


12

With some printf implementations (including GNU printf and the printf builtin of ksh93, zsh, bash and lksh (but not dash nor yash) on GNU systems) and assuming your system has a French (of France or Canada at least), or Swedish or Slovenian or Macedonian or Kyrgyz locale (and a few more, that is, those that have space as the thousand separator): $ LC_ALL=...


11

You may not want to use bc for this. Perhaps awk would work better: awk '{sum+=$1};END{print sum/NR}' /path/to/file


11

I found a nice answer on SO explaining the different fields: Real is wall clock time - time from start to finish of the call. This is all elapsed time including time slices used by other processes and time the process spends blocked (for example if it is waiting for I/O to complete). User is the amount of CPU time spent in user-mode code (outside the ...


11

bc can not output zero before decimal point, you can use printf: $ printf '%.3f\n' "$(echo "scale=3;1/8" | bc)" 0.125


11

In the simplest of the options, this does append to the pipe stream: $ echo "750/12.5" | { bc; echo "/24"; } 60 /24 However that has an unexpected newline, to avoid that you need to either use tr: $ echo "750/12.5" | { bc | tr -d '\n' ; echo "/24"; } 60/24 Or, given the fact that a command expansion removes trailing newlines: $ printf '%s' $( echo "750/...


11

Perhaps I am misinterpreting, but this language seems to disallow the syntax used in the above example. That example assumes GNU bc, which adds its own extensions to the bc language. As documented in its manual, you should use the -s switch to make it process the exact POSIX bc language, or the -w switch if you want it to warn about extensions: $ echo '1.2 ...


10

I will explain it from another perspective. To be fair, bc has advantage since it doesn't have to read anything from the disk and only needs its blob/binaries while python has to import a series of modules + reading a file. So your test might be biased towards bc. To actually test it you should use bc -q file where file contains: 6^6^6 quit Changing just ...


10

A basic difference between the two is that dc uses the reverse Polish notation. It requires explicit commands even in order to produce an output. You might add two integers in bc by saying: bc <<< "2+4" and it would produce 6 on a line by itself. However, in dc you'd need to say: dc <<< "2 4 +p" You can also do much fun stuff using ...


10

In bc, the solution is to divide by 1: $ bc -l <<<"scale=8; x=25*20; x" 500 $ bc -l <<<"scale=8; x=25*20; x/1" 500.00000000 So, your script could be like this: hypothenuse () { local a b c x y a=${1}; b=${2} echo "This is a ${a} and b ${b}" x=$(echo "scale=8; $a^2/1" | bc -l) y=$(echo "scale=8; $b^...


9

And a Perl one-(long)liner, including median: cat numbers.txt \ | perl -M'List::Util qw(sum max min)' -MPOSIX -0777 -a -ne 'printf "%-7s : %d\n"x4, "Min", min(@F), "Max", max(@F), "Average", sum(@F)/@F, "Median", sum( (sort {$a<=>$b} @F)[ int( $#F/2 ), ceil( $#F/2 ) ] )/2;' The special options used are: -0777 : read the whole file at once instead ...


9

A simple way is to use printf: $ printf "%.3f\n" 0.005000000000 0.005 To remove the leading 0, just parse it out with sed: $ printf "%.3f\n" 0.005000000000 | sed 's/^0//' .005


Only top voted, non community-wiki answers of a minimum length are eligible