mp-units icon indicating copy to clipboard operation
mp-units copied to clipboard

Odd behavior when taking a square root

Open khansson opened this issue 11 months ago • 7 comments

I'm playing around with this library, and I found some odd behavior

This is to calculate the average speed of a particle in a Maxwellian distribution.

I wrote something simple to do this

#include <type_traits>
#include <mp-units/systems/international/international.h>
#include <mp-units/systems/isq/space_and_time.h>
#include <mp-units/systems/si/unit_symbols.h>
#include <iostream>
#include "mp-units/math.h"

using namespace mp_units;

auto AverageSpeed(const QuantityOf<isq::thermodynamic_temperature> auto &Temperature, const QuantityOf<isq::mass> auto &Mass)
{
        const auto boltz =  mp_units::si::si2019::boltzmann_constant;
        constexpr double pi = std::numbers::pi;
        const auto Internal = 8.0 * boltz * Temperature / (pi * Mass);

        using namespace mp_units::si::unit_symbols;
        const QuantityOf< pow<2>(isq::velocity)> auto Internal_converted = value_cast<(m * m / (s*s))>( Internal);
        return mp_units::pow<1,2>(Internal); //Change Internal to Internal_converted in order to compile
}

int main()
{
  using namespace mp_units::si::unit_symbols;
  using namespace mp_units::international::unit_symbols;

  const auto Temp = 1000 * K;
  const auto Mass = 10 * Da;

  const auto particleSpeed = AverageSpeed(Temp, Mass);

  std::cout << particleSpeed[m / s].number() << std::endl;
}

This currently fails to compile with at magnitude.h line 310

  if (exp.den != 1) {
    std::terminate();  // Rational powers not yet supported
  }

I think its trying to take a square root of a boltzmann constant which is not allowed. The type of Internal seem measured in K * k_b / Da.

However, if I replace the return statement of my AverageSpeed function with

return mp_units::pow<1,2>(Internal_converted);

then everything compiles. Is there a good argument for why the value_cast in necessary here?

khansson avatar Jul 19 '23 20:07 khansson