Reputation: 815
Following code is written to rotate a point around the origin in 2D. However, instead of going on a circle, it keeps converging to the centre. (originally ran on Three.js) This code works absolutely correct. (I have done this in other platforms and even ran a numerical simulation in excel sheet too).
Why does this happen?
<body>
<div id="vals"></div>
<script>
theta = Math.PI / 90.0;
var x = 1;
var y = 1;
var element = document.getElementById("vals");
var i;
for (i = 0; i < 10000; i++){
var r = Math.sqrt( x * x + y * y );
var para = document.createElement("pre");
var node = document.createTextNode("x="+x+" y="+y+" r="+r);
para.appendChild(node);
element.appendChild(para);
x = (x * Math.cos(theta)) - (y * Math.sin(theta));
y = (y * Math.cos(theta)) + (x * Math.sin(theta));
}
</script>
</body>
p.s. I know that if I normalize the values and multiply by the magnitude , I would get the correct answer. However I want to know why this exact thing doesn't work.
Upvotes: 0
Views: 37
Reputation: 80187
At first, you apply changed x value to get y. It is just wrong. Instead remember old value and use it.
var tempx = x;
x = (x * Math.cos(theta)) - (y * Math.sin(theta));
y = (y * Math.cos(theta)) + (tempx * Math.sin(theta));
Second: reusing the same values causes error accumulation, so radius might converge - exactly as you see. So more exact approach is to store initial values and rotate them using current angle (not angle difference)
var x0 = 1;
var y0 = 1;
in the loop:
x = (x0 * Math.cos(theta * i)) - (y0 * Math.sin(theta * i));
y = (y0 * Math.cos(theta * i)) + (x0 * Math.sin(theta * i));
Upvotes: 1