2

I am trying to calculate below formula and store the value to a variable.

The pseudo code should look like:

a=10 b=5 c=$(((($a-$b)/52)) | bc -l) echo $c 

The result is empty. I couldn't figure out the syntax using bc. Please help me use bc instead of awk or other method.

2
  • 3
    also notes that if you need to do heavy computation with floating point etc, bash might not be the tool you should use for this!!! Each time you call bc you create a subprocess (system call user -> kernel mode, fork, exec,... then it takes time with memory allocation, new entry in the processes table, more work for the process scheduler, cache misses and eventually page misses, dynamic library might be loaded by bc,...) so you lose many CPU cycles. This would not be the case if you were using the appropriate language for this! Commented Mar 15, 2018 at 6:12
  • See: Division in script and floating-point Commented Mar 15, 2018 at 6:16

2 Answers 2

3

There are two things you need to be aware of. The first is that bc uses standard input for expressions so you would need to actually pipe your expression through it, or use the <<< redirection operator, one of:

c=$(echo "($a - $b) / 52" | bc) c=$(bc <<< "($a - $b) / 52") 

The <<< method is specific to bash and ksh (an possibly others, but I'm not really au fait with them). The other method can be used in most shells.

Secondly, you should be careful when using big numbers for this since bc has the annoying habit of splitting them across lines:

pax$ x=999999999999999999999999999999999999999999999999999999999999999999999 pax$ echo "$x / 7" | bc 14285714285714285714285714285714285714285714285714285714285714285714\ 2 

In order to avoid this, you need to change the line length:

pax$ echo "$x / 7" | BC_LINE_LENGTH=0 bc 142857142857142857142857142857142857142857142857142857142857142857142 
Sign up to request clarification or add additional context in comments.

Comments

3

You can use this:

a=10 b=5 c=$(bc -l <<< "($a-$b)/52") echo "$c" 

.09615384615384615384 

Or by setting a scale of 3:

c=$(bc -l <<< "scale=3; ($a-$b)/52") echo "$c" 

.096 

1 Comment

I picked paxdiablo as his/her answer is more comprehensive. Thanks for the attention!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.