OR-Tools  9.0
lp_print_utils.cc
Go to the documentation of this file.
1 // Copyright 2010-2021 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
15 
16 #include <cmath>
17 #include <cstdint>
18 #include <cstdio>
19 #include <limits>
20 
21 #include "absl/strings/str_cat.h"
23 #include "ortools/base/logging.h"
26 
27 namespace operations_research {
28 namespace glop {
29 
30 // Returns a string "num/den" representing the rational approximation of x.
31 // The absolute difference between the output fraction and the input "x" will
32 // not exceed "precision".
33 std::string StringifyRational(const double x, const double precision) {
34  if (x == kInfinity) {
35  return "inf";
36  } else if (x == -kInfinity) {
37  return "-inf";
38  }
39  Fraction fraction = RationalApproximation(x, precision);
40  const int64_t numerator = fraction.first;
41  const int64_t denominator = fraction.second;
42  return denominator == 1 ? absl::StrCat(numerator)
43  : absl::StrCat(numerator, "/", denominator);
44 }
45 
46 std::string Stringify(const Fractional x, bool fraction) {
47  return fraction ? StringifyRational(ToDouble(x),
48  std::numeric_limits<double>::epsilon())
49  : Stringify(x);
50 }
51 
52 // Returns a string that pretty-prints a monomial ax with coefficient
53 // a and variable name x
54 std::string StringifyMonomial(const Fractional a, const std::string& x,
55  bool fraction) {
56  if (a == 0.0) return "";
57  return a > 0.0
58  ? absl::StrCat(
59  " + ",
60  a == 1.0 ? x : absl::StrCat(Stringify(a, fraction), " ", x))
61  : absl::StrCat(
62  " - ", a == -1.0
63  ? x
64  : absl::StrCat(Stringify(-a, fraction), " ", x));
65 }
66 
67 } // namespace glop
68 } // namespace operations_research
int64_t a
std::string StringifyMonomial(const Fractional a, const std::string &x, bool fraction)
std::string Stringify(const Fractional x, bool fraction)
std::string StringifyRational(const double x, const double precision)
const double kInfinity
Definition: lp_types.h:84
static double ToDouble(double f)
Definition: lp_types.h:69
Collection of objects used to extend the Constraint Solver library.
Fraction RationalApproximation(const double x, const double precision)
std::pair< int64_t, int64_t > Fraction