-2

I am attempting to find the sum of a list of numbers' reciprocals. To illustrate what I am trying to do, here's a basic example:

With the file:

1  
2  
3  
4

I would be trying to find the sum of 1/1, 1/2, 1/3 and 1/4. Is there a simple bash one-liner to do this? (I am new to bash, so explanations would be welcome!)

mickp
  • 1,679
  • 7
  • 23
k-a-v
  • 326
  • 5
  • 22
  • This question has an answer here: https://stackoverflow.com/a/12722107/5411198 . You can't do floating point arithmetic only with bash. – builder-7000 Jan 01 '19 at 21:45

2 Answers2

2

You could do something like this:

sed 's|^|1/|' file | paste -sd+ | bc -l
  • sed 's|^|1/|' prepends 1/ to every line
  • paste -sd+ joins all lines with a plus sign creating an arithmetic expression 1/1+1/2+1/3+1/4
  • bc -l evaluates that arithmetic expression and outputs the result
mickp
  • 1,679
  • 7
  • 23
0

If you're looking for an arithmetical progression, you can use this bash one-liner using the bc command

d=0; for c in {1..4}; do d=`echo "$d + 1/$c" | bc -l`; done; echo "$d"

Its output is 1 + 0.5 + 0.3333 + 0.25 =

2.08333333333333333333

It works by

  1. Setting a variable named d to 0
  2. Creating a for loop that counts from 1 to 4
  3. In the for loop it sets the d variable to the new value $d + 1/$c passed to the bc -l command executing the arithmetic
  4. And outputs the value with an echo command
zx485
  • 28,498
  • 28
  • 50
  • 59