richelbilderbeek / boost_units_example_6

Boost.Units example 6: using an angle
https://github.com/richelbilderbeek/boost_units_examples
GNU General Public License v3.0
0 stars 0 forks source link

Improvement by email #1

Open richelbilderbeek opened 7 years ago

richelbilderbeek commented 7 years ago

Thanks to @samkramer for this suggestion:

I noticed that the code block for converting between the two units was commented out because it was > not working. I was able to resolve the issue by creating conversion functions -- please see below:

#include <iostream>
#include <iomanip>
#include <cmath>

#include <boost/math/constants/constants.hpp>
#include <boost/units/systems/angle/degrees.hpp>
#include <boost/units/systems/si/plane_angle.hpp>
#include <boost/units/systems/si/io.hpp>

const double PI = boost::math::constants::pi<double>();

using Angle = boost::units::quantity<boost::units::si::plane_angle>;

double ToDegrees(const Angle& angle)
{
    return static_cast<boost::units::quantity<boost::units::degree::plane_angle>>(angle).value();
}

double ToRadians(const Angle& angle)
{
    return static_cast<boost::units::quantity<boost::units::si::plane_angle>>(angle).value();
}

Angle Degrees(double angleInDegrees)
{
    return Angle(angleInDegrees * boost::units::degree::degrees);
}

Angle Radians(double angleInRadians)
{
    return Angle(angleInRadians * boost::units::si::radians);
}

int main() {
    const Angle delta(2.0 * PI * boost::units::si::radians / 16.0);
    const Angle turn(2.0 * PI * boost::units::si::radians);

    std::cout << std::setprecision(20);
    for (Angle i(0.0 * boost::units::si::radians); i < turn; i += delta) {
        std::cout << "sin(" << i << ") = " << std::sin(i.value()) << std::endl;
    }
    std::cout << "sin(" << turn << ") = " << std::sin(turn.value()) << std::endl;

    // Converting between radians and degrees --

    std::cout << "Angle (specified as radians) = " << turn << std::endl;

    double turnDegreesDecimal = ToDegrees(turn);
    std::cout << "Angle (ToDegrees conversion) = " << turnDegreesDecimal << std::endl;

    Angle turnDegrees = Degrees(turnDegreesDecimal);
    std::cout << "Angle (Degrees factory) = " << turnDegrees << std::endl;

    double turnRadians = ToRadians(turnDegrees);
    std::cout << "Angle (ToRadians conversion) = " << turnRadians << std::endl;
}
richelbilderbeek commented 7 years ago

I am sorry to state that I will not accept this suggestion, as it removes the units. Boost.Unit is about keeping units.

Would Sam find out how to display a boost::units::quantity<boost::units::si::plane_angle> in radians and degrees without conversion to plain doubles, I'd be happy to add it.