MATLAB: Decrease precision of decimal no value saved for a variable.

MATLABprecision

Hi, I wrote a script file and in that am solving some equations to get y1, y2. Now y1 = (some equation) and y2 = y1+2. Solving it I am getting y1 = -1.7383e-17 and y2 = 2 but I want it to solve and save values as either y1 = 0, y2 = 2 OR y1 = -1.7383e-17 and y2 = 2-(1.7383e-17) i.e, y2<2. I tried to set precision to 4 in beginning of my script file by giving command: digits(4); but still I am getting the same result. Thanks in advance.

Best Answer

You have overstepped the limits of what double floating-point numbers can represent. Because of that limit on floating-point precision, 2-1.7383e-17 is equivalent to 2:
>> fprintf('%.30f\n',2-1.7383e-17)
2.000000000000000000000000000000
Once easy solution would be to simply round to the same number of decimal places:
>> round([2,1.7383e-17]*1e15)/1e15
ans =
2 0