Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division in script and floating-point

Tags:

bash

shell

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 
like image 773
Paris31 Avatar asked Aug 27 '12 17:08

Paris31


People also ask

What is a floating point division?

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.

How do you float a division in Bash?

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.

What is the difference between floating point and integer division Explain with examples?

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.


2 Answers

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 ...)" 
like image 55
John Kugelman Avatar answered Sep 27 '22 20:09

John Kugelman


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) }') 
like image 41
jordanm Avatar answered Sep 27 '22 18:09

jordanm