cos block error (simulink)
10 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
기범
el 14 de En. de 2023
Comentada: Paul
el 17 de En. de 2023
why is this happen?
cos(pi/2) = 6.123e-17??
0 comentarios
Respuesta aceptada
John D'Errico
el 14 de En. de 2023
Editada: John D'Errico
el 14 de En. de 2023
Welcome to the wonderful, wacky world of floating point arithmetic.
Is the number
format long g
pi/2
EXACTLY pi/2?
cos(pi/2)
Of course not. Pi is an irrational number (even subtly worse, transcendental), so it cannot ever be represented exactly in double precision arithmetic, so not in any finite number of digits. And that means pi/2 as stored is just a tiny bit off from the exact value of pi/2. Consequently, cos(pi/2) is not EXACTLY zero. Close. To within floating point trash. But not exactly so.
If you want MATLAB to work in exact multiples of pi, you can do so, but that requires using the symbolic toolbox.
sym(pi/2)
cos(sym(pi/2))
5 comentarios
John D'Errico
el 16 de En. de 2023
So you would want a rather poor approximation to the cosine function for small values? That is, you would rather see an error of 1e-10, than an error of 1e-17? Why do I feel that is just a really, really, seriously bad idea? You want an exact value some of the time, but far more often, you are willing to accept a really poor approximation?
You could test to see if the absolute value is less then 1e-16, and if so, set that to zero. At last then you are not making a rather large error.
Más respuestas (1)
Paul
el 14 de En. de 2023
Base Simulink doesn't have a block that implements functions cosd or cospi. Maybe some other toolbox does. If not, both of those functions support code generation so you can use the Matlab Function block and call either (or both of them) from there.
5 comentarios
Paul
el 17 de En. de 2023
I never said to use syms. I did say to use cosd, etc. if you want have all your angles defined in degrees. So, if theta, phi, and psi are all in degrees on input, then we have
x = r.*sind(phi).*cosd(theta)
and similar for y and z
Ver también
Categorías
Más información sobre Number Theory 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!