极坐标不正确 - 笛卡尔坐标转换。 -0是什么意思?

时间:2015-06-22 14:52:12

标签: c++ polar-coordinates cartesian-coordinates

我从极坐标到笛卡尔坐标的转换不正确,反之亦然。我的代码产生奇怪的点,如(1,-0)。我正在使用this计算器检查我的转化情况。当我转换回笛卡尔坐标时,其中一次转换完全错误。

点b:(0,1)=> (1,1.5708)=> (0,0)

#include <math.h>
#include <iostream>
/* Title:      Polar - Cartesian Coordinate Conversion
*  References: HackerRank > All Domains > Mathematics > Geometry > Polar Angles
*              Cartesian to Polar: (radius = sqrt(x^2 + y^2), theta = atan(y/x))
*              Polar to Cartesian: (x = radius*cos(theta), y = radius*sin(theta))
*/

//General 2D coordinate pair
struct point{
    point(float a_val, float b_val) : a(a_val), b(b_val){;};
    point(void){;};
    float a, b;
};
//Converts 2D Cartesian coordinates to 2D Polar coordinates 
point to_polar(/*const*/ point& p){//*** Conversion of origin result in (r, -nan) ***
    point ans(sqrt(pow(p.a,2) + pow(p.b,2)), atan(p.b/p.a));
    return ans;
}
//Converts 2D Polar coordinates to 2D Cartesian coordinates
point to_cartesian(/*const*/ point& p){
    point ans(p.a * cos(p.b), p.a * sin(p.b));
    return ans;
}
//Outputs 2D coordinate pair
std::ostream& operator<<(std::ostream& stream, const point& p){
    stream << "(" << p.a << "," << p.b << ")";
    return stream;
}
int main(){
    //Test Points - Cartesian
    point a(0, 0);
    point b(0, 1);
    point c(1, 0);
    point d(0,-1);
    point e(-1,0); 

    //Print Cartesian/Rectangular points
    std::cout << "Cartesian Coordinates:" << std::endl;
    std::cout << a << std::endl;
    std::cout << b << std::endl;
    std::cout << c << std::endl;
    std::cout << d << std::endl;
    std::cout << e << std::endl; 

    //Print Cartesian to Polar
    std::cout << "Polar Coordinates:" << std::endl;
    std::cout << to_polar(a) << std::endl;//Failure (0,-nan)         
    std::cout << to_polar(b) << std::endl;//Success
    std::cout << to_polar(c) << std::endl;//Success
    std::cout << to_polar(d) << std::endl;//Success
    std::cout << to_polar(e) << std::endl;//Failure (1,-0)  

    //Print Polar to Cartesian
    std::cout << "Cartesian Coordinates:" << std::endl;
    std::cout << to_cartesian(a) << std::endl;//Success
    std::cout << to_cartesian(b) << std::endl;//Failure (0,0)
    std::cout << to_cartesian(c) << std::endl;//Success
    std::cout << to_cartesian(d) << std::endl;//Failure (0,-0)
    std::cout << to_cartesian(e) << std::endl;//Failure (-1,-0)


    return 0;
}

2 个答案:

答案 0 :(得分:3)

作为第一步,您需要在转换为极坐标时切换到atan2而不是atanatan给飞机的一半带来了错误的结果。

答案 1 :(得分:3)

您正在转换为笛卡儿已经是笛卡尔的点。你想要的是:

std::cout << "Cartesian Coordinates:" << std::endl;
std::cout << to_cartesian(to_polar(a)) << std::endl;
std::cout << to_cartesian(to_polar(b)) << std::endl;
//...

编辑:使用atan2解决了NaN问题,(0, 0)转换为(0, 0),这很好。