0

I'm doing a porting of a matlab project in C#, this snippet of matlab code fills griglia with decimal like 0.025, 0.075, 0.325

for xgriglia=x1+incxy/2:incxy:x2
        
        for ygriglia=y1+incxy/2:incxy:y2
            
            contagriglia=contagriglia+1;
            griglia(contagriglia,1)=xgriglia;
            griglia(contagriglia,2)=ygriglia;
            
            
        end
    end

I translated it in C# like so, (variables are all double)

for (var xgriglia = x1 + incxy / 2; xgriglia <= x2; xgriglia += incxy)
{
 for (var ygriglia = y1 + incxy / 2; ygriglia <= y2; ygriglia += incxy)
 {
  contagriglia++;
  griglia0[contagriglia - 1] = xgriglia;
  griglia1[contagriglia - 1] = ygriglia;
 }
}

but the results in griglia0 and gliglia1 are like: 0.075000000000000011, 0.32499999999999996, 0.37499999999999994

what is the cause of this? And how can I fix it?

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
Us3r
  • 41
  • 5
  • Please provide types of variables and rename if you can because they're extremely difficult to process mentally LOL – Ermiya Eskandary Oct 08 '21 at 09:48
  • Matlab is probably rounding the output so you don't see the imprecise nature of floating point arithmetic. This question may be a duplicate of https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate. You can "fix" it by formatting it to (say) 3 decimal places when displaying the numbers. – Matthew Watson Oct 08 '21 at 09:52
  • 1
    @MatthewWatson Added that one too – Luis Mendo Oct 08 '21 at 09:53
  • @ErmiyaEskandary variables are all double – Us3r Oct 08 '21 at 10:36

0 Answers0