Google OR-Tools v9.14
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
fp_utils.h
Go to the documentation of this file.
1// Copyright 2010-2025 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
14// Utility functions on IEEE floating-point numbers.
15// Implemented on float, double, and long double.
16//
17// Also a placeholder for tools controlling and checking FPU rounding modes.
18//
19// IMPORTANT NOTICE: you need to compile your binary with -frounding-math if
20// you want to use rounding modes.
21
22#ifndef OR_TOOLS_UTIL_FP_UTILS_H_
23#define OR_TOOLS_UTIL_FP_UTILS_H_
24
25#include <algorithm>
26#include <cmath>
27#include <cstdint>
28#include <cstdlib>
29#include <limits>
30// Needed before fenv_access. See https://github.com/microsoft/STL/issues/2613.
31#include <numeric> // IWYU pragma:keep.
32
33#include "absl/log/check.h"
34#include "absl/types/span.h"
35
36#if defined(_MSC_VER)
37#pragma fenv_access(on) // NOLINT
38#else
39#include <cfenv> // NOLINT
40#endif
41
42#ifdef __SSE__
43#include <xmmintrin.h>
44#endif
45
46#if defined(_MSC_VER)
47static inline double isnan(double value) { return _isnan(value); }
48static inline double round(double value) { return floor(value + 0.5); }
49#elif defined(__APPLE__) || __GNUC__ >= 5
50using std::isnan;
51#endif
52
53namespace operations_research {
54
55// ScopedFloatingPointEnv is used to easily enable Floating-point exceptions.
56// The initial state is automatically restored when the object is deleted.
57//
58// Note(user): For some reason, this causes an FPE exception to be triggered for
59// unknown reasons when compiled in 32 bits. Because of this, we do not turn
60// on FPE exception if __x86_64__ is not defined.
61//
62// TODO(user): Make it work on 32 bits.
63// TODO(user): Make it work on msvc, currently calls to _controlfp crash.
64
66 public:
68#if defined(_MSC_VER)
69 // saved_control_ = _controlfp(0, 0);
70#elif (defined(__GNUC__) || defined(__llvm__)) && defined(__x86_64__)
71 CHECK_EQ(0, fegetenv(&saved_fenv_));
72#endif
73 }
74
76#if defined(_MSC_VER)
77 // CHECK_EQ(saved_control_, _controlfp(saved_control_, 0xFFFFFFFF));
78#elif defined(__x86_64__) && defined(__GLIBC__)
79 CHECK_EQ(0, fesetenv(&saved_fenv_));
80#endif
81 }
82
83 void EnableExceptions(int excepts) {
84#if defined(_MSC_VER)
85 // _controlfp(static_cast<unsigned int>(excepts), _MCW_EM);
86#elif (defined(__GNUC__) || defined(__llvm__)) && defined(__x86_64__) && \
87 !defined(__ANDROID__)
88 CHECK_EQ(0, fegetenv(&fenv_));
89 excepts &= FE_ALL_EXCEPT;
90#if defined(__APPLE__)
91 fenv_.__control &= ~excepts;
92#elif (defined(__FreeBSD__) || defined(__OpenBSD__))
93 fenv_.__x87.__control &= ~excepts;
94#elif defined(__NetBSD__)
95 fenv_.x87.control &= ~excepts;
96#else // Linux
97 fenv_.__control_word &= ~excepts;
98#endif
99#if defined(__NetBSD__)
100 fenv_.mxcsr &= ~(excepts << 7);
101#else
102 fenv_.__mxcsr &= ~(excepts << 7);
103#endif
104 CHECK_EQ(0, fesetenv(&fenv_));
105#endif
106 }
107
108 private:
109#if defined(_MSC_VER)
110 // unsigned int saved_control_;
111#elif (defined(__GNUC__) || defined(__llvm__)) && defined(__x86_64__)
112 fenv_t fenv_;
113 mutable fenv_t saved_fenv_;
114#endif
115};
116
117template <typename FloatType>
118inline bool IsPositiveOrNegativeInfinity(FloatType x) {
119 return x == std::numeric_limits<FloatType>::infinity() ||
120 x == -std::numeric_limits<FloatType>::infinity();
121}
122
123// Tests whether x and y are close to one another using absolute and relative
124// tolerances.
125// Returns true if |x - y| <= a (with a being the absolute_tolerance).
126// The above case is useful for values that are close to zero.
127// Returns true if |x - y| <= max(|x|, |y|) * r. (with r being the relative
128// tolerance.)
129// The cases for infinities are treated separately to avoid generating NaNs.
130template <typename FloatType>
131bool AreWithinAbsoluteOrRelativeTolerances(FloatType x, FloatType y,
132 FloatType relative_tolerance,
133 FloatType absolute_tolerance) {
134 DCHECK_LE(0.0, relative_tolerance);
135 DCHECK_LE(0.0, absolute_tolerance);
136 DCHECK_GT(1.0, relative_tolerance);
138 return x == y;
139 }
140 const FloatType difference = fabs(x - y);
141 if (difference <= absolute_tolerance) {
142 return true;
143 }
144 const FloatType largest_magnitude = std::max(fabs(x), fabs(y));
145 return difference <= largest_magnitude * relative_tolerance;
146}
147
148// Tests whether x and y are close to one another using an absolute tolerance.
149// Returns true if |x - y| <= a (with a being the absolute_tolerance).
150// The cases for infinities are treated separately to avoid generating NaNs.
151template <typename FloatType>
152bool AreWithinAbsoluteTolerance(FloatType x, FloatType y,
153 FloatType absolute_tolerance) {
154 DCHECK_LE(0.0, absolute_tolerance);
156 return x == y;
157 }
158 return fabs(x - y) <= absolute_tolerance;
159}
160
161// Returns true if x is less than y or slighlty greater than y with the given
162// absolute or relative tolerance.
163template <typename FloatType>
164bool IsSmallerWithinTolerance(FloatType x, FloatType y, FloatType tolerance) {
165 if (IsPositiveOrNegativeInfinity(y)) return x <= y;
166 return x <= y + tolerance * std::max(FloatType(1.0),
167 std::min(std::abs(x), std::abs(y)));
168}
169
170// Returns true if x is within tolerance of any integer. Always returns
171// false for x equal to +/- infinity.
172template <typename FloatType>
173inline bool IsIntegerWithinTolerance(FloatType x, FloatType tolerance) {
174 DCHECK_LE(0.0, tolerance);
175 if (IsPositiveOrNegativeInfinity(x)) return false;
176 return std::abs(x - std::round(x)) <= tolerance;
177}
178
179// Handy alternatives to EXPECT_NEAR(), using relative and absolute tolerance
180// instead of relative tolerance only, and with a proper support for infinity.
181#define EXPECT_COMPARABLE(expected, obtained, epsilon) \
182 EXPECT_TRUE(operations_research::AreWithinAbsoluteOrRelativeTolerances( \
183 expected, obtained, epsilon, epsilon)) \
184 << obtained << " != expected value " << expected \
185 << " within epsilon = " << epsilon;
186
187#define EXPECT_NOTCOMPARABLE(expected, obtained, epsilon) \
188 EXPECT_FALSE(operations_research::AreWithinAbsoluteOrRelativeTolerances( \
189 expected, obtained, epsilon, epsilon)) \
190 << obtained << " == expected value " << expected \
191 << " within epsilon = " << epsilon;
192
193// Given an array of doubles, this computes a positive scaling factor such that
194// the scaled doubles can then be rounded to integers with little or no loss of
195// precision, and so that the L1 norm of these integers is <= max_sum. More
196// precisely, the following formulas will hold (x[i] is input[i], for brevity):
197// - For all i, |round(factor * x[i]) / factor - x[i]| <= error * |x[i]|
198// - The sum over i of |round(factor * x[i])| <= max_sum.
199//
200// The algorithm tries to minimize "error" (which is the relative error for one
201// coefficient). Note however than in really broken cases, the error might be
202// infinity and the factor zero.
203//
204// Note on the algorithm:
205// - It only uses factors of the form 2^n (i.e. ldexp(1.0, n)) for simplicity.
206// - The error will be zero in many practical instances. For example, if x
207// contains only integers with low magnitude; or if x contains doubles whose
208// exponents cover a small range.
209// - It chooses the factor as high as possible under the given constraints, as
210// a result the numbers produced may be large. To balance this, we recommend
211// to divide the scaled integers by their gcd() which will result in no loss
212// of precision and will help in many practical cases.
213//
214// TODO(user): incorporate the gcd computation here? The issue is that I am
215// not sure if I just do factor /= gcd that round(x * factor) will be the same.
216void GetBestScalingOfDoublesToInt64(absl::Span<const double> input,
217 int64_t max_absolute_sum,
218 double* scaling_factor,
219 double* max_relative_coeff_error);
220
221// Returns the scaling factor like above with the extra conditions:
222// - The sum over i of min(0, round(factor * x[i])) >= -max_sum.
223// - The sum over i of max(0, round(factor * x[i])) <= max_sum.
224// For any possible values of the x[i] such that x[i] is in [lb[i], ub[i]].
225double GetBestScalingOfDoublesToInt64(absl::Span<const double> input,
226 absl::Span<const double> lb,
227 absl::Span<const double> ub,
228 int64_t max_absolute_sum);
229// This computes:
230//
231// The max_relative_coeff_error, which is the maximum over all coeff of
232// |round(factor * x[i]) / (factor * x[i]) - 1|.
233//
234// The max_scaled_sum_error which is a bound on the maximum difference between
235// the exact scaled sum and the rounded one. One needs to divide this by
236// scaling_factor to have the maximum absolute error on the original sum.
237void ComputeScalingErrors(absl::Span<const double> input,
238 absl::Span<const double> lb,
239 absl::Span<const double> ub, double scaling_factor,
240 double* max_relative_coeff_error,
241 double* max_scaled_sum_error);
242
243// Returns the Greatest Common Divisor of the numbers
244// round(fabs(x[i] * scaling_factor)). The numbers 0 are ignored and if they are
245// all zero then the result is 1. Note that round(fabs()) is the same as
246// fabs(round()) since the numbers are rounded away from zero.
247int64_t ComputeGcdOfRoundedDoubles(absl::Span<const double> x,
248 double scaling_factor);
249
250// Returns alpha * x + (1 - alpha) * y.
251template <typename FloatType>
252inline FloatType Interpolate(FloatType x, FloatType y, FloatType alpha) {
253 return alpha * x + (1 - alpha) * y;
254}
255
256inline int fast_ilogb(double value) { return ilogb(value); }
257inline double fast_scalbn(double value, int exponent) {
258 return scalbn(value, exponent);
259}
260
261} // namespace operations_research
262
263#endif // OR_TOOLS_UTIL_FP_UTILS_H_
In SWIG mode, we don't want anything besides these top-level includes.
int fast_ilogb(double value)
Definition fp_utils.h:256
bool IsSmallerWithinTolerance(FloatType x, FloatType y, FloatType tolerance)
Definition fp_utils.h:164
bool IsIntegerWithinTolerance(FloatType x, FloatType tolerance)
Definition fp_utils.h:173
double fast_scalbn(double value, int exponent)
Definition fp_utils.h:257
double GetBestScalingOfDoublesToInt64(absl::Span< const double > input, absl::Span< const double > lb, absl::Span< const double > ub, int64_t max_absolute_sum)
Definition fp_utils.cc:184
FloatType Interpolate(FloatType x, FloatType y, FloatType alpha)
Returns alpha * x + (1 - alpha) * y.
Definition fp_utils.h:252
bool AreWithinAbsoluteOrRelativeTolerances(FloatType x, FloatType y, FloatType relative_tolerance, FloatType absolute_tolerance)
Definition fp_utils.h:131
bool AreWithinAbsoluteTolerance(FloatType x, FloatType y, FloatType absolute_tolerance)
Definition fp_utils.h:152
void ComputeScalingErrors(absl::Span< const double > input, absl::Span< const double > lb, absl::Span< const double > ub, double scaling_factor, double *max_relative_coeff_error, double *max_scaled_sum_error)
Definition fp_utils.cc:175
int64_t ComputeGcdOfRoundedDoubles(absl::Span< const double > x, double scaling_factor)
Definition fp_utils.cc:207
bool IsPositiveOrNegativeInfinity(FloatType x)
Definition fp_utils.h:118
static int input(yyscan_t yyscanner)