Alex Rivera | Logout

Division in script and floating-point

Asked 2012-08-27T17:57:51.323
50

I would like to do the following operation in my script:

1 - ((m - 20) / 34)

I would like to assign the result of this operation to another variable. I want my script use floating point math. For example, for m = 34:

results = 1 - ((34 - 20) / 34) == 0.588
Edit
Report

1 Answer

61

You could use the bc calculator. It will do arbitrary precision math using decimals (not binary floating point) if you set increease scale from its default of 0:

$ m=34
$ bc <<< "scale = 10; 1 - (($m - 20) / 34)"
.5882352942

The -l option will load the standard math library and default the scale to 20:

$ bc -l <<< "1 - (($m - 20) / 34)"
.58823529411764705883

You can then use printf to format the output, if you so choose:

printf "%.3f\n" "$(bc -l ...)"
answered 2012-08-27T18:09:24.107

Your Answer