Miguel P
Miguel P

Reputation: 1292

C++ Convert angles to coordinates

I'm currently trying to convert 2 angles into x, y, z, using a formula from Matlab from Mathworks, Sph2Cart

http://www.mathworks.com/help/techdoc/ref/sph2cart.html

Algorithm:

x = r .* cos(elevation) .* cos(azimuth)
y = r .* cos(elevation) .* sin(azimuth)
z = r .* sin(elevation)

In C++

clax = 1 * cos((Altitude/360)*(2*XM_PI)) * cos((Azimuth/360)*(2*XM_PI));
clay = 1 * sin((Altitude/360)*(2*XM_PI));
claz = 1 * cos((Altitude/360)*(2*XM_PI)) * sin((Azimuth/360)*(2*XM_PI));

But no matter what Altitude and Azimuth is, clax, clay and claz is either 0 or 1.

I'm sure that i made a mistake, and i will laugh after this how stupid i was. But really, i have no idea why this doesn't work, why the values only give 1 or 0 for each of them...

Upvotes: 0

Views: 1828

Answers (3)

Mehrwolf
Mehrwolf

Reputation: 8527

The problem are most likely the divisions Altitude/360 and Azimuth/360, when Altitude and Azimuth are integers. This will perform an integer division and you loose the fractions. As an illustrative example, try this code

#include <iostream>
#include <cmath>

int main()
{
    int angle = 90;
    std::cout << std::sin((angle/360)*(2*M_PI)) << std::endl;
    std::cout << std::sin((angle/360.0)*(2*M_PI)) << std::endl;
    std::cout << std::sin((angle/360.0)*(2.0*M_PI)) << std::endl;
    return 0;
}

which outputs

0
1
1

Note that the first zero is obviously incorrect.

To fix your code, simply change the integer constants from 360 to double-constants 360.0.

Upvotes: 1

Chip
Chip

Reputation: 3316

Not sure if this is helpful, but works for me....

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    double XM_PI = 3.14159;
    double Altitude = 32;
    double Azimuth = 24;
    double clax = 1 * cos((Altitude/360)*(2*XM_PI)) * cos((Azimuth/360)*(2*XM_PI));
    double clay = 1 * sin((Altitude/360)*(2*XM_PI));
    double claz = 1 * cos((Altitude/360)*(2*XM_PI)) * sin((Azimuth/360)*(2*XM_PI));
    std::cout << "clax=" << clax << endl;
    std::cout << "clay=" << clay << endl;
    std::cout << "claz=" << claz << endl;
}

Answer :

clax=0.774731
clay=0.529919
claz=0.344932

As others have said, make sure all variables are float/double. Also check what XM_PI is. If it is 0 somehow, that would explain your result.

Upvotes: 1

bitmask
bitmask

Reputation: 34618

In all likelihood, you declared clax as some integer type (e.g. int, long, ...). Otherwise, Altitude or Azimuth might be declared as integer types. In that case you would always wind up with multiples of 2*pi in the arguments to the trigonometric functions.

Upvotes: 3

Related Questions