Rotating a point in 2D shows inaccurate result

I'm trying to create a member function called 'rotated' in class 'Point'. However when I try to rotate (1,0) by 180 degrees , I get the output as 0.00555556,-4.35155e-17 instead of (-1,0).

Where did it all go wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
 
#include <cmath>
#include <ostream>
#include <iomanip>


class Point
{
   

public:
 
    double x;
    double y;  
 
 
     Point( ){
       x=0;
       y=0;
 
}

Point(double a, double b): x(a), y(b) {
 
}


    // methods
Point rotated (const double angle) {
     
     Point r;
     r.x = (x)*cos(angle*M_PI)/180 - (y)*sin(angle*M_PI)/180;
     r.y = (x)*sin(angle*M_PI)/180 + (y)*cos(angle*M_PI)/180 ;
     
     
     return r;
     }
    
};


#include <iostream>
using namespace std;
 
int main()
{
    // example, replace with your tests

    
    Point a(1,0);
     
    Point rota;
    
    rota=a.rotated(90);
    
 
    cout<<rota.x<<","<<rota.y<<'\n';
    
return 0;    
}


0.00555556,-4.35155e-17
Last edited on
should it be


cos(angle*M_PI/180) instead to get it into radians for cos?
and sin similar?

you can also factor out the sine and cosine, rather than fetch that number multiple times.

also
-4.35155e-17
is effectively zero, so be aware of this kind of thing as you look at the values.
Last edited on
 
(angle*M_PI)/180
should be
 
(angle*M_PI/180)
To maintain compatibility with all the other trig functions, I'd define the angle in rotated() to be in radians, not degrees. If someone wants to rotate by degrees, let them (the caller) do the conversion:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Rotate "this" by "angle" radians and return the result
Point rotated (const double angle) {
     Point r;
     r.x = (x)*cos(angle) - (y)*sin(angle);
     r.y = (x)*sin(angle) + (y)*cos(angle) ;
     return r;
}
...
int main()
{
    // example, replace with your tests
    Point a(1,0);
    Point rota;
    rota=a.rotated(90*M_PI/180);
    cout<<rota.x<<","<<rota.y<<'\n';
    
return 0;    
}
Changing it to (angle*M_PI/180) worked and gave (-1, 1.22465e-16).
Thank you all! :D

Last edited on
Topic archived. No new replies allowed.