简体   繁体   中英

Eigen C++: Best Way To Convert 2D Polar To Cartesian

I am currently doing:

Eigen::Vector2d polar(2.5, 3 * M_PI / 4);
Eigen::Vector2d cartesian = polar.x() * Vector2d(cos(polar.y()), sin(polar.y()));

but I'm not sure if this is the correct way to use Eigen or if there is some better built in way.

Thanks!

That looks right to me if you're wanting to stick with using Eigen.

Generally though since the polar representation has angles, it might be good to avoid using the Eigen::Vector2d just for the sake of reducing mistakes that may be made in the future (like adding multiple angles together and not dealing with the fact that 0 == 2*PI). Maybe you could do it with structs instead:

struct Polar { double range; double angle; };
struct Cartesian { double x; double y; };

Cartesian to_cartesian(const Polar& p) {
    double c = cos(p.angle);
    double s = sin(p.angle);
    return {p.range * c, p.range * s};
}

Polar to_polar(const Cartesian& c) {
    return {std::sqrt(c.x * c.x + c.y * c.y), std::atan2(c.y, c.x)};
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM