Decrease precision of decimal no value saved for a variable.

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.

1 Comment

The MATLAB function digits is in the Symbolic Toolbox. Are you using any symbolic operators?

Sign in to comment.

 Accepted 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

3 Comments

Hi Stephen, thanks for answering but it doesn't solve my problem as it is also rounding value of 2.5687 to 3 which is not required. Let me elaborate my problem. In my script file I have parameters x1,x2,x3,x4,y1,y2,y3,y4,z1,z2,z3,z4. Now I am giving equations to solve x1,y1,z1. Now rest of the parameters are calculated using x1,y1,z1 as x1=x2=x3=x4, z1=z2=z3=z4, y2=y1+2, y3=y1+3, y4=y1+5. Now after getting all these parameters I have certain if() cases to calculate a parameter(say calC). Now look at one specific if() case.
if (y1<0 && y2<y1+2 && y3<y1+3 && y4<y1+5)
calC=(some value);
end
if(y1==0 && y2==y1+2 && y3==y1+3 && y4==y1+5)
calC=(some value);
end
Now in total I have 11 such cases depending on different conditions on y1, y2, y3, y4. Now my problem is that when MATLAB is solving y1 = -1.7383e-17, it is giving y2=2, y3=3, y4=5 but if y1 is negative it should have gone into first if() condition but it is not going because of y2, y3, y4 and as per values of y2, y3, y4 it should have gone into second case but it isn't going into it also. My problem is that it isn't going into any of if() case, even if it has gone into any one if() case my purpose would have been served. I don't need much precision and precision upto 4 decimal places is enough for me. Sorry for such long text and thanks for your valuable time.
@Ashutosh Kumar: "it is also rounding value of 2.5687 to 3 "
Really? Not when I try it:
>> round(2.5687*1e15)/1e15
ans = 2.5687
Did you actually follow my example (note the two factors of 1e15 that I used), or did you just use round by itself?
Hi Stephen I got my mistake and round() function worked on for me. Thanks alot for help.

Sign in to comment.

More Answers (0)

Products

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!