When I compute sinc(pi) I get a small non-zero number, but I know that sin(pi)/pi should equal zero. How do I get sinc(pi) to equal zero in Matlab? For that matter, even sin(pi) doesn't return a value of zero (and it should) so I can't replace sinc(x) with sin(x)/x to get the right answer
>> sinc(pi)
ans =
-0.0436
>> sin(pi)
ans =
1.2246e-16

 채택된 답변

Jeremy
Jeremy 2019년 11월 7일
편집: Jeremy 2019년 11월 7일

0 개 추천

Since pi is an irrational number and cannot be represented exactly by a finite number of binary digits, there is always going to be an infintesimal error assocated with doing math with irrational numbers (really, there is always an error doing arithmetic on a computer). If you really want it to be zero you can compare it to a tolerance and say that any number smaller than your tolerance is set to zero. For example:
tol = 1e-15;
z = sin(pi);
if abs(z) < tol
z = 0;
end
Alternatively, you could use
round
round(sin(pi),15)
will return 0

댓글 수: 1

Karen Norris
Karen Norris 2019년 11월 7일
Thanks! I prefer this to writing the bit of logic to force a zero.

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

추가 답변 (1개)

Steven Lord
Steven Lord 2019년 11월 7일

0 개 추천

The pi function does not return π but a value very close to π as Jeremy Marcyoniak stated. Using a tolerance or rounding are two approaches to get sin(x) to return 0 when x is pi. Two others:
1) Compute symbolically. The sym function can recognize the number returned by pi (see the description of the 'r' value for the flag input on its documentation page) and treat it as π.
>> P = sym(pi);
>> sin(P)
ans =
0
2) Use the sinpi function introduced in release R2018b.
>> s = sinpi(0:2)
s =
0 0 0

댓글 수: 1

Karen Norris
Karen Norris 2019년 11월 7일
Super. I like these solutions. Thank you.

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

카테고리

도움말 센터File Exchange에서 Mathematics에 대해 자세히 알아보기

태그

질문:

2019년 11월 7일

댓글:

2019년 11월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by