Math using dc
suggest changedc
is one of the oldest language on Unix.
It is using the reverse polish notation, which means that you are first stacking numbers, then operations. For example 1+1
is written as 1 1+
.
To print an element from the top of the stack use command p
echo '2 3 + p' | dc
5
or
dc <<< '2 3 + p'
5
You can print the top element many times
dc <<< '1 1 + p 2 + p'
2
4
For negative numbers use \_
prefix
dc <<< '_1 p'
-1
You can also use capital letters from A to F
for numbers between 10 and 15
and .
as a decimal point
dc <<< 'A.4 p'
10.4
dc
is using abitrary precision which means that the precision is limited only by the available memory. By default the precision is set to 0 decimals
dc <<< '4 3 / p'
1
We can increase the precision using command k
. 2k
will use
dc <<< '2k 4 3 / p'
1.33
dc <<< '4k 4 3 / p'
1.3333
You can also use it over multiple lines
dc << EOF
1 1 +
3 *
p
EOF
6
bc is a preprocessor for dc.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents