Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
lp_print_utils.cc
Go to the documentation of this file.
1// Copyright 2010-2024 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"
23#include "absl/strings/string_view.h"
26
27namespace operations_research {
28namespace 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".
33std::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
46std::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
54std::string StringifyMonomial(const Fractional a, absl::string_view 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
Definition table.cc:44
std::string StringifyRational(const double x, const double precision)
std::string Stringify(const Fractional x, bool fraction)
std::string StringifyMonomial(const Fractional a, absl::string_view x, bool fraction)
static double ToDouble(double f)
Definition lp_types.h:74
In SWIG mode, we don't want anything besides these top-level includes.
Fraction RationalApproximation(const double x, const double precision)
std::pair< int64_t, int64_t > Fraction
const Variable x
Definition qp_tests.cc:127