Advertisement

sin cos

Started by January 04, 2003 08:10 PM
3 comments, last by Ronin Magus 22 years, 1 month ago
I''m trying to rotate a 2d vector by an angle. So my equation would be y = sin(a + b), x = cos(a + b).. I think. Using those fun identities I came up with this: y = y * cos(angle) + x * sin(angle) x = x * cos(angle) - y * sin(angle) So I wrote this simple little program:
  
#include <iostream>
#include <math.h>

using namespace std;

int main()
{
    float angle;
    float x, y;
    
    cout << "Enter an x y value: ";
    cin >> x >> y;
    
    cout << "Enter a rotation angle: ";
    cin >> angle;
    
    cout << "New x and y: " << (x * cos(angle) - y * sin(angle)) << " " << (y * cos(angle) + x * sin(angle)) << endl;

    
    return 0;
}
  
So I expect when I enter 1, 1 as the vector, and rotate by 180 degrees, I should get -1, -1. But instead, I get these results: Enter an x y value: 1 1 Enter a rotation angle: 180 New x and y: 0.202693 -1.39961 That''s WAY off!! What could I be doing wrong? Is the error in my formula? In the program? Rounding errors? Those are some pretty darn big rounding errors if so. Any ideas?
aut viam inveniam aut faciam MoonStar Projects
Well, right off the bat I noticed that you are specifying angles in degrees. If you specify them in radians, your problem should be solved. Try rotating by PI. Or, add the extra line in your code to convert from degrees to radians:

angle = 3.141592654/180 * angle;

Or, you can use M_PI (I forget which header that is included in)


Merowe
Advertisement
Doh! I''ve been out of my math class too long, flat forgot about that Thank you!

But still, even when I convert from degrees to rads, by doing (pi/180 * angle) I get -.996394 and -1.00359 when I''m expecting -1 and -1. Is this the closest I can expect to get?

500 error once...twice...THRICE...FOUR TIMES!!...


aut viam inveniam aut faciam

MoonStar Projects
I had the same rude revelation with sinf and cosf yesterday.

Try doing this:
value = sinf(degrees/57.2957);

That is because there are 57.2957 degrees in a radian...
Ronin Magus, you should use a more precise version of pi. A lot of compilers provide a constant M_PI in . You can initialize a global variable with atan(1)*4 if your compiler doesn''t provide one.

Anyway, for any serious application, you forget degrees and use radians all the time.

This topic is closed to new replies.

Advertisement