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

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

本文关键字:是什么 意思 不正确 转换 笛卡尔 坐标 极坐标      更新时间:2023-10-16

从极坐标到笛卡尔坐标的转换不正确,反之亦然。我的代码会产生一些奇怪的点,比如(1,-0)。我用这个计算器来检查我的转换。另外,当我转换回笛卡尔坐标时,其中一个转换是完全错误的。

点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;
}

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

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

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