Search code examples
matlabprecisionresolutiondeviation

Is there a reason MATLAB is giving me deviations as I perform the calculations?


I have these random Gaussian variables A and B to represent voltages. I also have resistances in series with the voltages, RA and RB, respectively. I want to take voltage measurements in between RA and RB, and I want to measure the current from A to B. I have implemented,

I = (A-B)/(RA+RB);
U = I*RA-A;

Let's say RA has a high value, RH, but I want to use process of elimination to find out. I have implemented,

A_calc = U+I*RL; %guess the low value first

Now I want to check if the calculation matches.

if A_calc==A
    disp('RA=RL');
else
    disp('RA=RH');
end

Now the issue is, A_calc is never equal to A. There are always deviations, no matter what I set the resistance value to.

What could be the error? Is it the resolution lost? I thought MATLAB was 16 bits of resolution?


Solution

  • I'd need the entire code to figure out where your problem is - but in general, it is very common to find numerical inaccuracies in such computations. You almost always define some kind of difference threshold, under it the variables are considered equal. Please use:

    function eq = isalmostequal(a,b,tol)
    if ~exist('tol','var'); 
       tol = 1e-9;
    end
    
    eq = (abs(a - b) < tol)
    end
    

    call it:

    if isalmostequal(A,A_calc)
       disp('RA=RL');
    else
       disp('RA=RH');
    end