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
A floating point division where a number divides another number can be expressed as. Thus it can be said that in a floating point division, mantissas are divided and exponents are subtracted. The major steps for a floating point division are. Extract the sign of the result from the two sign bits.
While you can't use floating point division in Bash you can use fixed point division. All that you need to do is multiply your integers by a power of 10 and then divide off the integer part and use a modulo operation to get the fractional part. Rounding as needed.
If one or two sides has a floating point number, then it means floating point division. The result of integer division is always an integer. Integer division determines how many times one integer goes into another. The remainder after integer division is simply dropped, no matter how big it is.
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 ...)"
Bash does not do floating point math. You can use awk or bc to handle this. Here is an awk example:
$ m=34; awk -v m=$m 'BEGIN { print 1 - ((m - 20) / 34) }' 0.588235
To assign the output to a variable:
var=$(awk -v m=$m 'BEGIN { print 1 - ((m - 20) / 34) }')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With