floating point with Shell script

Soo-Hyun Choi soohyunc at users.sourceforge.net
Mon Feb 13 16:00:50 UTC 2006


Yeh, I just relised that floating point arithmetic may not be always
accurate as Tony mentioned here. I changed my way to use integer
comparison.

Cheers,
SH

On 2/12/06, Tony Arnold <tony.arnold at manchester.ac.uk> wrote:
>
>
> Soo-Hyun Choi wrote:
> > Hi,
> >
> > This may be a little bit off-topic.
> >
> > I would like to do some floating point arithmetic with shell script
> > programming as the below.
> >
> > if [ floating_number_01 = floating_number_02]; then
> >    do-some-work
> > else
> >    do-some-other-work
> > fi
> >
> >
> > I know shell script cannot deal the floating point directly. Then, how
> > do I deal with the above flow control statement?
>
> You may want to consider using a scripting language such as PERL or
> Python that understands floating point numbers. I don;t know of a way to
> do this with bash.
>
> However, it is never a good idea to compare two floating point numbers
> for equality in any language! Represetnation of floating point numbers
> on a computer is only an approximation and arithmetic can introduce
> small errors in the least significant bits, enough to cause comparisons
> of apparently equal values to return not equal!
>
> If you must compare two floating point numbers, then the best way is to
> subtract the two numbers and compare the absolute of the result against
> a small number, e.g.,
>
>         if (abs(a-b) < 0.0001)
>                 do some work.
>
> Regards,
> Tony.
> --
> Tony Arnold, IT Security Coordinator, University of Manchester,
> IT Services Division, Kilburn Building, Oxford Road, Manchester M13 9PL.
> T: +44 (0)161 275 6093, F: +44 (0)870 136 1004, M: +44 (0)773 330 0039
> E: tony.arnold at manchester.ac.uk, H: http://www.man.ac.uk/Tony.Arnold
>
> --
> ubuntu-users mailing list
> ubuntu-users at lists.ubuntu.com
> https://lists.ubuntu.com/mailman/listinfo/ubuntu-users
>




More information about the ubuntu-users mailing list