OR-Tools  9.6
lp_print_utils.cc
Go to the documentation of this file.
1 // Copyright 2010-2022 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 #include <string>
21 
22 #include "absl/strings/str_cat.h"
24 #include "ortools/base/logging.h"
27 
28 namespace operations_research {
29 namespace glop {
30 
31 // Returns a string "num/den" representing the rational approximation of x.
32 // The absolute difference between the output fraction and the input "x" will
33 // not exceed "precision".
34 std::string StringifyRational(const double x, const double precision) {
35  if (x == kInfinity) {
36  return "inf";
37  } else if (x == -kInfinity) {
38  return "-inf";
39  }
40  Fraction fraction = RationalApproximation(x, precision);
41  const int64_t numerator = fraction.first;
42  const int64_t denominator = fraction.second;
43  return denominator == 1 ? absl::StrCat(numerator)
44  : absl::StrCat(numerator, "/", denominator);
45 }
46 
47 std::string Stringify(const Fractional x, bool fraction) {
48  return fraction ? StringifyRational(ToDouble(x),
49  std::numeric_limits<double>::epsilon())
50  : Stringify(x);
51 }
52 
53 // Returns a string that pretty-prints a monomial ax with coefficient
54 // a and variable name x
55 std::string StringifyMonomial(const Fractional a, const std::string& x,
56  bool fraction) {
57  if (a == 0.0) return "";
58  return a > 0.0
59  ? absl::StrCat(
60  " + ",
61  a == 1.0 ? x : absl::StrCat(Stringify(a, fraction), " ", x))
62  : absl::StrCat(
63  " - ", a == -1.0
64  ? x
65  : absl::StrCat(Stringify(-a, fraction), " ", x));
66 }
67 
68 } // namespace glop
69 } // 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)
constexpr double kInfinity
Definition: lp_types.h:88
std::string StringifyRational(const double x, const double precision)
static double ToDouble(double f)
Definition: lp_types.h:73
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