PSCF v1.5.0
Rational.cpp
1/*
2* Util Package - C++ Utilities for Scientific Computation
3*
4* Copyright 2010 - 2017, David Morse (morse012@um.edu)
5* Distributed under the terms of the GNU General Public License.
6*/
7
8#include "Rational.h"
9#ifdef UTIL_MPI
10#include <util/mpi/MpiStructBuilder.h>
11#endif
12
13namespace Util
14{
15
16 #ifdef UTIL_MPI
17 /*
18 * Initialize MPI Datatype.
19 */
20 MPI::Datatype MpiTraits<Rational>::type = MPI::BYTE;
21 bool MpiTraits<Rational>::hasType = false;
22
23 /*
24 * Commit MPI Datatype.
25 */
26 void Rational::commitMpiType()
27 {
28 if (!MpiTraits<Rational>::hasType) {
29 MpiStructBuilder builder;
30 Rational object;
31 builder.setBase(&object);
32 builder.addMember(&object.num_, MPI::INT);
33 builder.addMember(&object.den_, MPI::INT);
34 builder.commit(MpiTraits<Rational>::type);
35 MpiTraits<Rational>::hasType = true;
36 }
37 }
38 #endif
39
40 /*
41 * Output stream inserter for a Rational.
42 */
43 std::ostream& operator << (std::ostream& out, Rational const &a)
44 {
45 UTIL_CHECK(a.den_ > 0);
46 out << a.num_;
47 if (a.den_ != 1) {
48 out << "/" << a.den_ ;
49 }
50 return out;
51 }
52
53 #ifdef UTIL_CXX11
54 /*
55 * Input stream extractor for a Rational.
56 */
57 std::istream& operator >> (std::istream& in, Rational &a)
58 {
59 std::string word;
60 in >> word;
61 int size = word.size();
62
63 // Search for '/' character in word
64 std::size_t slashId = word.find('/');
65 bool hasSlash = false;
66 if (slashId != std::string::npos) {
67 hasSlash = true;
68 }
69
70 // Extract numerator and denominator
71 if (hasSlash) {
72 UTIL_CHECK(slashId > 0);
73 UTIL_CHECK((int)slashId < size - 1);
74 int numSize = slashId;
75 int denSize = size - slashId - 1;
76 std::string numStr = word.substr(0, numSize);
77 std::string denStr = word.substr(slashId + 1, denSize);
78 a.num_ = std::stoi(numStr);
79 a.den_ = std::stoi(denStr);
80 } else {
81 a.num_ = std::stoi(word);
82 a.den_ = 1;
83 }
84 UTIL_CHECK(a.den_ > 0);
85
86 // Store the reduced form, as the constructors do: operator ==
87 // compares numerators and denominators
88 a.reduce();
89
90 return in;
91 }
92 #endif
93
94}
A Rational number (a ratio of integers).
Definition Rational.h:34
Rational()
Default constructor.
Definition Rational.h:271
#define UTIL_CHECK(condition)
Assertion macro suitable for serial or parallel production code.
Definition global.h:68
Utility classes for scientific computation.
std::istream & operator>>(std::istream &in, Pair< Data > &pair)
Input a Pair from an istream.
Definition Pair.h:44
std::ostream & operator<<(std::ostream &out, const Pair< Data > &pair)
Output a Pair to an ostream, without line breaks.
Definition Pair.h:57