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

Incorrect Polar - Cartesian Coordinate Conversions. What does -0 Mean?

我从极坐标到笛卡尔坐标的转换不正确,反之亦然。我的代码产生奇怪的点,如 (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;
}

作为第一步,您需要在转换为极坐标时切换到 atan2 而不是 atanatan 给出半个平面的错误结果。

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

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) 很好。