Floating-point arithmetic in UNIX shell script

2019-01-09 07:41发布

问题:

How to do arithmetic with floating point numbers such as 1.503923 in a shell script? The floating point numbers are pulled from a file as a string. The format of the file is as follows:

1.5493482,3.49384,33.284732,23.043852,2.2384...
3.384,3.282342,23.043852,2.23284,8.39283...
.
.
.

Here is some simplified sample code I need to get working. Everything works fine up to the arithmetic. I pull a line from the file, then pull multiple values from that line. I think this would cut down on search processing time as these files are huge.

# set vars, loops etc.

while [ $line_no -gt 0 ]
do
    line_string=`sed -n $line_no'p' $file_path`  # Pull Line (str) from a file
    string1=${line_string:9:6}                   # Pull value from the Line
    string2=${line_string:16:6}
    string3=...
    .
    .
    .
    calc1= `expr $string2 - $string7` |bc -l     # I tried these and various
    calc2= ` "$string3" * "$string2" ` |bc -l    # other combinations
    calc3= `expr $string2 - $string1`
    calc4= "$string2 + $string8" |bc
    .
    .
    .
    generic_function_call                        # Use the variables in functions
    line_no=`expr $line_no - 1`                  # Counter--
done

Output I keep getting:

expr: non-numeric argument
command not found

回答1:

What about this?

calc=$(echo "$String2 + $String8"|bc)

This will make bc to add the values of $String2 and $String8 and saves the result in the variable calc.



回答2:

I believe you should use : bc

For example:

echo "scale = 10; 123.456789/345.345345" | bc

(It's the unix way: each tool specializes to do well what they are supposed to do, and they all work together to do great things. don't emulate a great tool with another, make them work together.)

Output:

.3574879198

Or with a scale of 1 instead of 10:

echo "scale = 1; 123.456789/345.345345" | bc

Output:

.3

Note that this does not perform rounding.



回答3:

If you don't have the "bc" you can jast use 'awk' :

calc=$(echo 2.3 4.6 | awk '{ printf "%f", $1 + $2 }')


回答4:

scale in bc is the precission so with a scale of 4 if you type bc <<< 'scale=4;22.0/7' you get 3.1428 as an answer. If you use a scale of 8 you get 3.14285714 which is 8 numbers after the floating point. So the scale is a precission factor