mpusz / mp-units

The quantities and units library for C++
https://mpusz.github.io/mp-units/
MIT License
997 stars 79 forks source link

Getting energy from power and time. #482

Closed magni-mar closed 10 months ago

magni-mar commented 10 months ago

When trying to calculate energy from multiplying power and time, as in: energy = power * time.

I get the following error:

error: no match for ‘operator*’ (operand types are ‘Watt’ {aka ‘units::quantity<units::isq::si::dim_power, units::isq::si::watt, double>’} and ‘std::chrono::seconds’ {aka ‘std::chrono::duration<long int>’})
   13 |     Joule motor{motor_power_at_melting * mix_time};
      |                 ~~~~~~~~~~~~~~~~~~~~~~ ^ ~~~~~~~~
      |                 |                        |
      |                 |                        std::chrono::seconds {aka std::chrono::duration<long int>}
      |                 Watt {aka units::quantity<units::isq::si::dim_power, units::isq::si::watt, double>}

for the following code:

#include <iostream>
#include <chrono>
#include <units/isq/si/energy.h>
#include <units/isq/si/power.h>

using Watt = units::aliases::isq::si::power::W<double>;
using std::chrono::seconds;
using Joule = units::aliases::isq::si::energy::J<double>;

auto main() -> int {
    Watt motor_power_at_melting{1000};
    seconds mix_time{10};
    Joule motor{motor_power_at_melting * mix_time};
}

How can I multiply power with time without accessing the raw numbers?

mpusz commented 10 months ago

You can't directly divide mp_units::quantity by std::chrono::seconds. Those are different libraries and the division of such variables will not produce power (in fact it is an invalid operation by default).

In order to make it work you have to convert std::chrono::seconds to a proper quantity type in mp-units. I notice you are still on the V1 of the library but here is the solution in the V2: https://godbolt.org/z/5qTsfq7MY. Similar stuff can be easily achieved in the previous versions as well.

magni-mar commented 10 months ago

I missed the type that covers seconds in mp units.