MATLAB: 1.1 + 0.1 == 1.2 returns false bugdouble precisionfloating pointnot a bug Very strange. Apparently this is related to the precision of the double type as 1.1 + 0.1 - 1.2 = 2.2204e-16 What can I do to counter this behavior? Thanks! Best Answer See the FAQ: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F It has strategies to deal with this situation, such as comparing the value to a tolerance.% instead of a == b% use:areEssentiallyEqual = abs(a-b) < tol% for some small value of tol relative to a and b% perhaps defined using eps(a) and/or eps(b) Related SolutionsMATLAB: Rounding using ‘fix’… possibly a bug To see what is going on you can examine the exact floating point values. Note that none of your original numbers except 0.5 can be represented in IEEE double format exactly:>> num2strexact(.7)ans =0.6999999999999999555910790149937383830547332763671875>> num2strexact(.5)ans =0.5>> num2strexact(.4)ans =0.40000000000000002220446049250313080847263336181640625>> num2strexact(.3)ans =0.299999999999999988897769753748434595763683319091796875>> num2strexact(.1)ans =0.1000000000000000055511151231257827021181583404541015625>> num2strexact(.7/.1)ans =6.99999999999999911182158029987476766109466552734375>> num2strexact(.5/.1)ans =5>> num2strexact(.4/.1)ans =4>> num2strexact(.3/.1)ans =2.999999999999999555910790149937383830547332763671875You can find num2strexact here:http://www.mathworks.com/matlabcentral/fileexchange/22239-num2strexact-exact-version-of-num2str MATLAB: How to convert a 64 bit, two’s complement value(binary vector)[ 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1] into a signed integer swapbytes(typecast(uint8(bin2dec(char(reshape(fliplr(A),8,[]).' + '0'))),'int64')) Related QuestionIs there a way to floor to a specified number of digitsMatrix[1,1,1,1;-1,-1,-1,-1;1,1,1,1] to vector[1,1,1,1,-1,-1,-1,-1,1,1,1,1]6*0.003125 – 0.018750 = 0, right? How to get the right answer-1 and 1 matrixVERY odd error with simple multiplication … OK… not so odd.Two equal numbers are not equal
Best Answer