Limiting Precision on MATLAB

조회 수: 10 (최근 30일)
Robert Dominski
Robert Dominski 2018년 2월 26일
답변: Robert Dominski 2018년 2월 26일
I have a condition for a switch statement. For example:
% Program variables and input prompts
runProgram = 1;
i = 1;
prompt_massRatio = 'Enter m/M Ratio: ';
prompt_Us = 'Enter Static friction: ';
prompt_Uk = 'Enter kinetic friction: ';
prompt_theta = 'Enter block angle: ';
% Graph variables F vs. m/M
Fplot = [];
massFraction = [];
% Program start
while runProgram == 1
% Calculation Variables
m_M = input(prompt_massRatio);
angle = input(prompt_theta);
theta = angle*(pi/180);
Us = input(prompt_Us);
Uk = input(prompt_Uk);
g = 9.81;
T = m_M*g;
W = g*sin(theta);
Fs = cos(theta)*g*Us;
Fk = cos(theta)*g*Uk;
% Conditions
forceSum = T - W;
switch (true)
case (forceSum < 0)
In this case, when forceSum is calculated for the conditions of m_M = 0.5, angle = 30, we get a value that is essentially zero but MATLAB does not read it as zero for the case statement. I.E. forceSum returns 8.8818e-016.
Any idea of making MATLAB read this value as 0?
Thanks for any help.

채택된 답변

David Fletcher
David Fletcher 2018년 2월 26일
Could try forceSum=int32(T-W)

추가 답변 (3개)

James Tursa
James Tursa 2018년 2월 26일
편집: James Tursa 2018년 2월 26일
With floating point calculations you often need to use tolerances, so this
if( forceSum < 0 )
would be coded something like this instead
if( abs(forceSum) < tol ) % for some appropriate tolerance
So all of your conditional tests should probably be modified into some type of tolerance test.

Walter Roberson
Walter Roberson 2018년 2월 26일

Robert Dominski
Robert Dominski 2018년 2월 26일
Thanks for the help and links. It worked.
Cheers! You guys are great.

카테고리

Help CenterFile Exchange에서 Get Started with MuPAD에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by