Getting wrong values for sin

20 visualizaciones (últimos 30 días)
Shaival Parikh
Shaival Parikh el 5 de Feb. de 2021
Comentada: Steven Lord el 5 de Feb. de 2021
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?

Respuestas (2)

Stuart Song
Stuart Song el 5 de Feb. de 2021
Because in matlab, pi = 3.1416 so you won't get 0 for sin(pi). You can try sinpi(1).
  1 comentario
Steven Lord
Steven Lord el 5 de Feb. de 2021
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

Iniciar sesión para comentar.


KALYAN ACHARJYA
KALYAN ACHARJYA el 5 de Feb. de 2021
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

Categorías

Más información sobre Trigonometry en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by