C++
C++なのでコンパイル時になんやかんやできるやつを探してたらBoostであった
Boost.Units を使えば良い.(http://www.boost.org/doc/libs/1_64_0/doc/html/boost_units.html)
sample
使用例として,簡単な問題を解いてみる.
h=634m地点から初速v0=2.4m/sでm=5kgのボールを落とす. ボールにかかる力は重力のみとすると,何秒で地面に到達するか.
#include <iostream> #include <boost/units/systems/si.hpp> #include <boost/units/io.hpp> #include <boost/units/pow.hpp> #include <boost/units/cmath.hpp> #include <boost/mpl/arithmetic.hpp> using namespace boost::units; // create new unit!! typedef boost::mpl::times<length_dimension,mass_dimension>::type LM_type; typedef unit<LM_type, si::system> kurenaif; int main() { const quantity<si::length> height = 634.0 * (si::meter); //x0 = 634m const quantity<si::mass> m = 5 * (si::kilogramme); const quantity<si::velocity> v0 = 2.4 * (si::meter / si::second); // const quantity<si::force> F = m*v0; compile error!!! because of invalid unit type const quantity<si::acceleration> g = 9.8 * (si::meter/pow<2>(si::second)); //create new unit!!! const quantity<kurenaif> test = height*m; const quantity<si::force> F = m*g; const quantity<si::time> t = -(v0 - sqrt(v0*v0+2.0*g*height))/g; std::cout << "height(x0) = " << height << std::endl; std::cout << "weight = " << m << std::endl; std::cout << "init. velocity = " << v0 << std::endl; std::cout << "g: " << g << std::endl; std::cout << "kurenaif:" << test << std::endl; std::cout << "force:" << F << std::endl; std::cout << "time:" << t << std::endl; return 0; } /* output height(x0) = 634 m weight = 5 kg init. velocity = 2.4 m s^-1 g: 9.8 m s^-2 kurenaif:3170 m kg force:49 m kg s^-2 time:11.1326 s */
memo
- 次元間違えはコンパイル時エラー
- auto型使えます