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