Output a small number as zero

조회 수: 31 (최근 30일)
S Crombie
S Crombie 2018년 2월 28일
댓글: Stephen23 2018년 3월 1일
If I type cos(pi/2) the answer comes back as 6.1232e-17 where I know, of course, that the correct answer is zero. What is the best way to get MATLAB intelligently to output zero in place of these very small numbers?
This came up when I was computing a rotation matrix using angles which were simple fractions of pi and one of the elements returned was 24678615572571482867467662723121/6582018229284824168619876730229402019930943462534319453394436096
which ideally would have been rounded to zero.

채택된 답변

Birdman
Birdman 2018년 2월 28일
편집: Birdman 2018년 2월 28일
Firstly, you need to read this:
Then, you may do this:
a=cos(pi/2);
if abs(a)<1e-6
a=0;
end
Note that 1e-6 is a tolerance value that user specifies, you can change it if you want.
  댓글 수: 5
S Crombie
S Crombie 2018년 2월 28일
Maybe my problem is more to do with the way my matrix is being created - it comes from a function which multiplies two matrices. If I call the function by passing numeric values it returns sensible 0.0000 values in the output but if I pass it a mixture of numeric values and symbolic variables it comes back with ridiculous fractions like the one I quoted in the first post.
If I apply a logical test to the matrix eg A < 1e-6 it doesn't test the elements and output true or false it simply adds < 1/1000000 on the end of each element. Is it treating my matrix as if it's composed of text strings?
Stephen23
Stephen23 2018년 3월 1일
" Is it treating my matrix as if it's composed of text strings?"
If they are symbolic variables then it is treating them as symbolic variables. Most likely the problem is how you define those symbolic variable values, e.g. first defining them as double before converting to symbolic, but unless you show us your code then we will have to rely on our magic crystal balls to know.
If you want help then ask a new question and give a minimum working example.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Number Theory에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by