Getting wrong values for sin

Hello, I was trying to plot a sine wave but was getting wrong values for the sine values:
sin(pi)
ans =
1.2246e-16
But at the same time all the cosine values I was getting were correct:
cos(2*pi)
ans =
1
Where am I going wrong and what am I supposed to do?

Answers (2)

Stuart Song
Stuart Song on 5 Feb 2021
Because in matlab, pi = 3.1416 so you won't get 0 for sin(pi). You can try sinpi(1).

1 Comment

Not exactly. The pi function does not return 3.1416. It is just displayed that way in the default display format.
format
x = pi
x = 3.1416
Changing the display format changes the value that is displayed though the number stored in memory does not change.
format longg
y = pi
y =
3.14159265358979
x == y % true
ans = logical
1
But neither does pi return the exact value of the irrational number π. Your computer doesn't have enough memory to store all the (infinite number of) digits of π.
I agree with your suggestion of sinpi if you know you're computing the sine of a multiple of π. Another potential option would be to work in degrees and use sind.
[sin(pi);
sinpi(1);
sind(180)]
ans = 3×1
1.22464679914735e-16 0 0

Sign in to comment.

You are not doing anything wrong here.
Have you see the complate long sin or any other trigonometric series, it all beacuse of long floting points calculation. Please see there are multiple threads related to floating number calulations issue
If you are insisted to get sin(pi) or cos(2pi) to be 0 and 1, you may try following way
>> pi_dat=radtodeg(pi)
pi_dat =
180
>> sind(pi_dat)
ans =
0
>> cosd(2*pi_dat)
ans =
1

Categories

Asked:

on 5 Feb 2021

Commented:

on 5 Feb 2021

Community Treasure Hunt

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

Start Hunting!