Why in matlab sin(pi) is not zero but sin(pi/2) is 1?

125 views (last 30 days)
Hello I know pi is 3.141596... I have a question. In MATLAB, sin(pi) is not zero because pi is note accurate, but sin(pi/2) is exactly 1. Why?
  1 Comment
Adam
Adam on 5 Sep 2016
You should generally be needing to consider whether sin(pi) is truly zero or not. If you ever need to do equality tests on floating point data it should always be done within a sensible tolerance anyway and within such a tolerance sin(pi) is equal to 0.

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 5 Sep 2016
You know how in Monopoly, there is a Community Chest card that says "Bank error in your favor, collect $200" ? Well, floating point round-off is like that: sometimes it works against you and sometimes it works with you.
The actual sin() calculation would be implemented as a hardware instruction.
  1 Comment
Walter Roberson
Walter Roberson on 28 Oct 2022
Let us examine the behaviour of sine near :
syms delta
Pi = sym(pi);
taylor(sin(Pi/2 + delta), delta, 0, 'Order', 10)
ans = 
The difference between MATLAB's pi() and the abstract π should be at most -- MATLAB's pi() would be the closest representable number to π . So less than 3e-16 difference in value against the true π . Now look through the taylor series and see that with δ being 0 < δ < 1, the powers of positive integer powers of δ are all less than delta, and the largest contribution would be from . But with δ being on the order of 3e-16, the square of it divided by 2 would be on the order of 4.5e-32 . And when you add that to 1, it is not going to make any difference to the 1.
How about sine near 0?
syms delta
Pi = sym(pi);
taylor(sin(Pi + delta), delta, 0, 'Order', 10)
ans = 
With δ being small near eps, the higher-order powers are going to be negligible, but the δ will remain -- so any inexact representation of π will potentially lead to a non-zero outcome. And recall that in floating point, the while the closest floating point number to π will be within a single bit of π the absolute error will be on the order of eps(pi) . With pi being between 2 and 4, that will be at least 2*eps(1) -- so while the error in representing π might be within a single bit of π that is on the order of 2 bits of error relative to representing 1 ... so Yes, it gets to be notable compared to 0.

Sign in to comment.


Mike Croucher
Mike Croucher on 21 Oct 2022
Edited: Hans Scharler on 27 Oct 2022
If you ever need to compute sin(x*pi) or cos(x*pi), its better to do sinpi(x) or cospi(x). You never explicitly multily x by a floating point approximation of pi so you always get the results you expect.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!