Re: floating point comparison

*To*: mathgroup at smc.vnet.net*Subject*: [mg95263] Re: floating point comparison*From*: dh <dh at metrohm.com>*Date*: Tue, 13 Jan 2009 07:03:16 -0500 (EST)*References*: <gkgp8r$3vg$1@smc.vnet.net>

Hi Bert, due to finite precision, it is not a good idea to accurately compare machine numbers. Therefore, some "grey zone" is usually defined. In Mathematica , from the manual: "Approximate numbers are considered unequal if they differ beyond their last two decimal digit" Now, what are the last 2 digits? Consider: 1.0 != 1.00000000000001 this gives False, both nu numbers are in agreement for digit 1..14, they differ in the 15. digit. Now consider: 1.0 - 1.00000000000001 != 0 this gives True because the numbers 1.0 - 1.00000000000001 and 0 already differ in the first digit. hope this helps, Daniel Bert Aerts (rm X) wrote: > In the code shown below, the result of iterFixedPointList[Cos,0.0] in 94 > iterations is equal to FixedPointList[Cos,0.0]. The while loop comparison > happens as newV - oldV != 0.0. However if the comparison is written as > newV != oldV, then the there are only 82 iterations and the result is not > the final one. Why are these 2 comparisons not equal? > > Remark: machine precision numbers are best shown in 16 digits precision: > Global Mathematica definition in Edit / Preferences : Appearance / > Numbers / Formatting / Displayed Precision = 16 in Mathematica 7.0.0 x86_64 > on Linux > > Clear[iterFixedPointList]; > iterFixedPointList[function_, initValue_] := > Module[{i, oldV, newV, listV}, > i = 1; > oldV = initValue; > newV = function[initValue]; > listV = {oldV, newV}; > While[newV - oldV != 0.0, > i++; > oldV = newV; > newV = function[newV]; > listV = Append[listV, newV]; > (* > Appending newV here already before it is tested > makes that the last 2 values in listV will be equal > *) > ]; > Print["Number of iterations is ", i]; > listV > ] > > >