简体   繁体   中英

How to approximate vector rotation

I have a point moving with the speed V(vectorX, vectorY). Initially V = (1, 0). I repeatedly rotate it by random angle using:

vectorX = vectorX * Math.cos(radianAngle) - vectorY * Math.sin(radianAngle);
vectorY = vectorX * Math.sin(radianAngle) + vectorY * Math.cos(radianAngle);

Rotation should not adjust vector length. But this solution decreases my vector length overtime:

0.9999999164020167
0.9989817245134542
0.9990928546670482
0.9990920078686215
0.9990307271300217
0.9990123195664165
0.9990122314933966
0.9958140526821458
0.9953881407397223
0.9953002497794944
0.9953739080312035
0.9953762669739241
0.9951229086200286
0.9951022010798389
0.9950609497602859
0.9950608230271147
0.9948941861659032
0.9949385678072231

I know that sin and cos functions give approximated results. But why exactly I get decreasing length? And how it can be solved?

Welcome to the world of non-exact floating-point arithmetic. You lose precision. That's a fact of life.

You should probably rotate the initial fixed vector by an increasing angle instead.

Ie:

angle = angle + radianAngle;
vectorX = initialVectorX * Math.cos(angle) - initialVectorY * Math.sin(angle);
vectorY = initialVectorX * Math.sin(angle) + initialVectorY * Math.cos(angle);

This way you won't accumulate precision loss.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM