1

I want to calculate the difference between two negative floating numbers and subsequently check if the result is below a certain threshold. The numbers are stored in the file.dat, since this calculation will be done many times the calculation has to rely on getting the values directly from a file without manual formatting. The file.dat looks for example like this.

-.63354975E+03 -.63354982E+03

Now since bash can't handle floats I've tried bc in the following way:

paste -sd- file.dat | bc >> file.dat

The paste command turns the input into

-.63354975E+03--.63354982E+03

bc should subract them, however I get the error message (standard_in) 1: syntax error. I could use sed to change one number to positive and then add them, but is there a way to do it directly with bc?


A different problem occurs when I use paste -sd+ file.dat | bc >> file.dat. This should add the numbers, the result is however 4.932900412, way off the expected 1267.09957. When I type in the calculation with the numbers formatted as -633.54975+-633.54982 I get the expected result. So it seems bc does not process numbers with exponents properly. Is there a way to resolve this?

5
  • 3
    The problem is the lack of whitespace (to delimit the numbers into separate tokens) I think - you could try replacing paste -sd- by pr -T -S' - ' -2 (pr allows string delimiters, whereas AFAIK paste only allows a single character) Commented Jan 16, 2019 at 13:39
  • Alright, this does the trick, but the second problem kicks in. The result from the example is 6.000000070 instead of 0.00007. When I change the number format to -633.54... the result is correct. Do you know how to resolve this? Then the answer would be complete. Commented Jan 16, 2019 at 13:45
  • 2
    for number format with expopnent see stackoverflow.com/questions/12882611/… There is an additional problem when you use the same file file.dat both as input argument and for output redirection. Commented Jan 16, 2019 at 13:46
  • @steeldriver Alright in this case please formulate an answer so I can accept it. Commented Jan 16, 2019 at 13:51
  • If you're going to use sed to modify the exponent, then you may as well use it for inserting the operator as well e.g. sed -e '$!N;s/\n/ - /' -e '...' Commented Jan 16, 2019 at 16:48

1 Answer 1

0

awk solution:

awk 'NR==1{a=$0};NR==2{b=$0};END{print (a)-(b)}' file.dat 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.