How to make a turn in R ^ 2?

I am stuck with a seemingly simple problem in mathematics: I need to rotate points in a two-dimensional Cartesian coordinate system, i.e. I have a point given (x / y) and an angular gamma, and I need to get the coordinates of this point when rotating the gamma ...

example: if x = 2 and y = 0, and the rotation angle is 90 Β°, the resulting point will be x '= 0, y' = -2 (rotated clockwise)

so I found this formula on the net ( http://en.wikipedia.org/wiki/Rotation_matrix ) and injected some code to test it:

$x = 1; echo "x: " . $x . "<br>"; $y = 1; echo "y: " . $y . "<br>"; $gamma = 45; echo "gamma: " . $gamma . "<br>"; $sinGamma = sin(deg2rad($gamma)); $cosGamma = cos(deg2rad($gamma)); $x2 = $x*$cosGamma - $y*$sinGamma; echo "x2: " . $x2 . "<br>"; $y2 = $y*$cosGamma + $x*$sinGamma; echo "y2: " . $y2 . "<br>"; 

while it works just BIG for angles of 90/180/270 degrees, everything else will lead to complete crap!

i.e:.

if x = 1 and y = 1 and gamma = 45 Β°, the resulting point will be located exactly along the x axis ... well - above the script:

 x: 1 y: 1 gamma: 45 x2: 1.11022302463E-16 y2: 1.41421356237 

I realized what is wrong? (school for a long time for me ^^), how can I do it right?

+4
source share
2 answers

Your numbers actually look pretty straight there - (1,1), rotated 45 degrees around the origin, will be (0, sqrt (2)). x2 looks weird because of the 1 in front, but the E-16 actually means the number .000000000000000111022 or something like that. And sqrt (2) comes out somewhere around 1.414.

You won’t get accurate results due to the rounding error with floating point (not to mention the fact that you are working with irrational numbers).

+4
source

Your code is correct. The fact that your example does not end exactly on the y axis is due to an extremely inaccurate floating point calculation, which you still cannot avoid if you want to rotate the real coordinate points.

+1
source

All Articles