precisionmatlab-compilerlanguage-concepts

How can i make my rounds() function in MATLAB, be very precised when handling around 400 values at a time?


I have made this function rounds() which rounds the values to the nearest multiple of 0.5, ie, rounds(2.685)=2.5 rounds(2.332)=2.5 rounds(2.7554)=3.0 rounds(2.245)=2.0 it works well in the way mentioned above, but while handling large number of values the precision drop. It does not give me the desired results. I have 30 functions, each of them computes 14 values which I pass in rounds() as a whole vector containing those 14 values. The results are like, for values for which it should return 3.0 such as rounds(2.7554) it only returns 2.5 and that affects my overall accuracy alot. Individually it works well for all values even 2.7554 returns 3.0 when i pass it to check its working. Can anyone tell me why this happens that while handling large number of values its performance decreases and also tell me the solution.

 function [newVal] = rounds(x) 
   dist = mod(x, 0.5); 
   floorVal = x - dist; 
   if  dist  >=0.25
     newVal = floorVal + 0.5;      
   else
     newVal = floorVal;
   end
 end 

The above is the rounds function and below i am showing how i have used it my functions.

if true
  calc(1) = x+y;
  calc(2) = x-y;
  calc(3) = x*y+a;
  .......
  .......
  .......
  calc(14) = a+b*c+x;
  calc = calc';
  final_calc = rounds(calc);
end

Even in a single function the rounds function handles only 14 values at once still the result is not precised, while if i pass those same values individually it gives the correct output. Please solve this issue someone. Thanks in advance.


Solution

  • function [newVal] = rounds2(x)
      newVal = round(x/0.5)*0.5;
    end
    

    This was something i was struggling for a long time but here I have now a perfect answer. This was happening because i was passing the vector expression dist >= 0.25 to if...end, incorrectly thinking that the if...end will be evaluated separately for each element of x(i). Hope that it helps some others too