blob: acda5ee9438f4f087520e656f6d34715a3ef4cd7 [file] [log] [blame]
Brian Silvermana8ce4c32018-08-04 23:57:09 -07001// Boost.Units - A C++ library for zero-overhead dimensional analysis and
2// unit/quantity manipulation and conversion
3//
4// Copyright (C) 2003-2008 Matthias Christian Schabel
5// Copyright (C) 2008 Steven Watanabe
6//
7// Distributed under the Boost Software License, Version 1.0. (See
8// accompanying file LICENSE_1_0.txt or copy at
9// http://www.boost.org/LICENSE_1_0.txt)
10
11/**
12\file tutorial.cpp
13
14\brief Basic tutorial using SI units.
15
16\details
17Tutorial
18Defines a function that computes the work, in joules,
19done by exerting a force in newtons over a specified distance
20in meters and outputs the result to std::cout.
21
22Also code for computing the complex impedance
23using std::complex<double> as the value type.
24
25Output:
26@verbatim
27//[tutorial_output
28F = 2 N
29dx = 2 m
30E = 4 J
31
32V = (12.5,0) V
33I = (3,4) A
34Z = (1.5,-2) Ohm
35I*Z = (12.5,0) V
36I*Z == V? true
37//]
38@endverbatim
39*/
40
41//[tutorial_code
42#include <complex>
43#include <iostream>
44
45#include <boost/typeof/std/complex.hpp>
46
47#include <boost/units/systems/si/energy.hpp>
48#include <boost/units/systems/si/force.hpp>
49#include <boost/units/systems/si/length.hpp>
50#include <boost/units/systems/si/electric_potential.hpp>
51#include <boost/units/systems/si/current.hpp>
52#include <boost/units/systems/si/resistance.hpp>
53#include <boost/units/systems/si/io.hpp>
54
55using namespace boost::units;
56using namespace boost::units::si;
57
58constexpr
59quantity<energy>
60work(const quantity<force>& F, const quantity<length>& dx)
61{
62 return F * dx; // Defines the relation: work = force * distance.
63}
64
65int main()
66{
67 /// Test calculation of work.
68 quantity<force> F(2.0 * newton); // Define a quantity of force.
69 quantity<length> dx(2.0 * meter); // and a distance,
70 quantity<energy> E(work(F,dx)); // and calculate the work done.
71
72 std::cout << "F = " << F << std::endl
73 << "dx = " << dx << std::endl
74 << "E = " << E << std::endl
75 << std::endl;
76
77 /// Test and check complex quantities.
78 typedef std::complex<double> complex_type; // double real and imaginary parts.
79
80 // Define some complex electrical quantities.
81 quantity<electric_potential, complex_type> v = complex_type(12.5, 0.0) * volts;
82 quantity<current, complex_type> i = complex_type(3.0, 4.0) * amperes;
83 quantity<resistance, complex_type> z = complex_type(1.5, -2.0) * ohms;
84
85 std::cout << "V = " << v << std::endl
86 << "I = " << i << std::endl
87 << "Z = " << z << std::endl
88 // Calculate from Ohm's law voltage = current * resistance.
89 << "I * Z = " << i * z << std::endl
90 // Check defined V is equal to calculated.
91 << "I * Z == V? " << std::boolalpha << (i * z == v) << std::endl
92 << std::endl;
93 return 0;
94}
95//]