views:

45

answers:

2

hi there!

i'm stuck with a seemingly simple problem in mathematics: i need to rotate points in a 2-dimensional cartesian coordinate system, i.e. i have a point given by (x/y) and an angle gamma and i need to get the coordinates of this point if rotated by gamma...

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

so i found this formula on the net (http://en.wikipedia.org/wiki/Rotation_matrix) and implemented 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 this works just GREAT for angles of 90/180/270 degrees, anything else would result in total crap!

i.e.:

if x=1 and y=1 and gamma=45°, the resulting point would lay exactly on the x-axis... well - the script above would output:

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

did i understand sth wrong? (school's over a long time for me ^^) how do i get this right?

+4  A: 

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

You're not going to get exact results due to floating-point rounding error (not to mention you're working with irrational numbers).

cHao
Exactly. Floating point arithmetic `!=` real number arithmetic
NullUserException
+1: It's due to floating point precision issues (See the [docs on floats](http://us3.php.net/manual/en/language.types.float.php) )
ircmaxell
+1  A: 

Your code is correct. The fact that your example doesn't end up exactly on the y axis is only due to inherently inexact floating point calculation, which you can't avoid anyway, if you want to rotate real-coordinate points.

jpalecek