Differences between revisions 1 and 58 (spanning 57 versions)
Revision 1 as of 2007-05-02 23:08:44
Size: 1939
Editor: redondos
Comment:
Revision 58 as of 2008-12-19 02:36:16
Size: 344
Editor: 126
Comment: 3.33333333333333
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:
[[Anchor(faq22)]]
== How can I calculate with floating point numbers instead of just integers? ==
["BASH"] does not have built-in floating point arithmetic:

{{{
    $ echo $((10/3))
    3
}}}

For better precision, an external program must be used, e.g. {{{bc}}}, {{{awk}}} or {{{dc}}}:

{{{
    $ echo "scale=3; 10/3" | bc
    3.333
}}}

The "scale=3" command notifies {{{bc}}} that three digits of precision after the decimal point are required.

If you are trying to compare floating point numbers, be aware that a simple ''x < y'' is not supported by all versions of {{{bc}}}. Alternatively, you could use this:

{{{
    if [[ $(bc <<< "1.4 - 2.5") = -* ]]; then
        echo "1.4 is less than 2.5."
    fi
}}}

This example substracts 2.5 from 1.4, and checks the sign of the result. If it is negative, the former number is less than the latter.

{{{awk}}} can be used for calculations, too:

{{{
    $ awk 'BEGIN {printf "%.3f\n", 10 / 3}' /dev/null
    3.333
}}}

There is a subtle but important difference between the {{{bc}}} and the {{{awk}}} solution here: {{{bc}}} reads commands and expressions ''from standard input''. {{{awk}}} on the other hand evaluates the expression as ''part of the program''. Expressions on standard input are ''not'' evaluated, i.e. {{{echo 10/3 | awk '{print $0}'}}} will print {{{10/3}}} instead of the evaluated result of the expression.

This explains why the example uses {{{/dev/null}}} as an input file for {{{awk}}}: the program evaluates the {{{BEGIN}}} action, evaluating the expression and printing the result. Afterwards the work is already done: it reads its standard input, gets an end-of-file indication, and terminates. If no file had been specified, {{{awk}}} would wait for data on standard input.

Newer versions of KornShell93 have built-in floating point arithmetic, together with mathematical functions like {{{sin()}}} or {{{cos()}}} .
Hi all!!! Always wondered what had happened to you after the accident vodka so http://dinergf.blogspirit.com/tag/chicken chicken chick, http://plantsgf.wikidot.com/system:page-tags/tag/syrup wine hand, http://dinergf.blogspirit.com/tag/kitchen beer insect, http://dinergf.wikidot.com/system:page-tags/tag/milk vodka, Thank you for good job!

Hi all!!! Always wondered what had happened to you after the accident vodka so http://dinergf.blogspirit.com/tag/chicken chicken chick, http://plantsgf.wikidot.com/system:page-tags/tag/syrup wine hand, http://dinergf.blogspirit.com/tag/kitchen beer insect, http://dinergf.wikidot.com/system:page-tags/tag/milk vodka, Thank you for good job!

BashFAQ/022 (last edited 2021-09-01 06:31:58 by geirha)