-1

I am trying to create function responsible for finding divisor of 90 figure smaller than given tempMaxAngle. For example my function should return 6 for tempMaxAngle=7 or 30 for tempMaxAngle=31 or 22.5 for tempMaxAngle=23, etc. Unfortunately it is not working correctly - I am getting strange values. Here is my algorythm:

function maxAngle = angletest(tempMaxAngle)
    format long g;
    tempMaxAngle = tempMaxAngle*10;
    tempMaxAngle = floor(tempMaxAngle)/10;
    while mod(90,tempMaxAngle)>0
        modResult =mod(90,tempMaxAngle)
        tempMaxAngle = tempMaxAngle - 0.1
    end
    maxAngle=tempMaxAngle;
end

partial result for tempMaxAngle=7 (while section result):

tempMaxAngle =

                   6.9


modResult =

     0.299999999999995


tempMaxAngle =

                   6.8


 modResult =

      1.59999999999999


tempMaxAngle =

                   6.7


modResult =

      2.89999999999998


tempMaxAngle =

                   6.6


modResult =

      4.19999999999998


tempMaxAngle =

                   6.5


modResult =

      5.49999999999998


tempMaxAngle =

                   6.4


modResult =

     0.399999999999966


tempMaxAngle =

                   6.3


modResult =

      1.79999999999996


tempMaxAngle =

                   6.2


modResult =

      3.19999999999997


tempMaxAngle =

                   6.1


modResult =

      4.59999999999996


tempMaxAngle =

                     6


modResult =

      5.99999999999995


tempMaxAngle =

                   5.9


modResult =

      1.49999999999994


tempMaxAngle =

                   5.8


modResult =

      2.99999999999993


tempMaxAngle =

                   5.7


modResult =

      4.49999999999993


tempMaxAngle =

      5.60000000000001


modResult =

     0.399999999999929

Why it keeps returing that kind of values instead of simple 6.9, 6.8, 6.7, etc. and similar for modulo function? How can I fix it?

Arxas
  • 241
  • 2
  • 4
  • 13
  • Why are you not doing `mod(90,7)` directly? – Oleg Aug 29 '13 at 18:36
  • Because it's a function that I would like to use for other values, not only 7. – Arxas Aug 29 '13 at 18:53
  • Now I get the question, it should read: find `x ≤ tempAngle` that divides 90 evenly. – Oleg Aug 29 '13 at 19:05
  • Don't understand what you are doing, but based on the textual description: have a look at finding the GCD http://stackoverflow.com/questions/11098274/greatest-common-divisor-of-multiple-more-than-2-numbers – Dennis Jaheruddin Aug 30 '13 at 08:36

1 Answers1

5

It is due to small errors in the internal floating representation.

Have a look at matlab double comparison

Community
  • 1
  • 1
Eyal
  • 66
  • 2