Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
mathutil.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
14#if defined(_MSC_VER)
15#define _USE_MATH_DEFINES
16#include <cmath>
17#endif
18
21
22namespace operations_research {
23
24// The formula is extracted from the following page
25// http://en.wikipedia.org/w/index.php?title=Stirling%27s_approximation
26double MathUtil::Stirling(double n) {
27 static const double kLog2Pi = log(2 * M_PI);
28 const double logN = log(n);
29 return (n * logN - n + 0.5 * (kLog2Pi + logN) // 0.5 * log(2 * M_PI * n)
30 + 1 / (12 * n) - 1 / (360 * n * n * n));
31}
32
33double MathUtil::LogCombinations(int n, int k) {
34 CHECK_GE(n, k);
35 CHECK_GT(n, 0);
36 CHECK_GE(k, 0);
37
38 // use symmetry to pick the shorter calculation
39 if (k > n / 2) {
40 k = n - k;
41 }
42
43 // If we have more than 30 logarithms to calculate, we'll use
44 // Stirling's approximation for log(n!).
45 if (k > 15) {
46 return Stirling(n) - Stirling(k) - Stirling(n - k);
47 } else {
48 double result = 0;
49 for (int i = 1; i <= k; i++) {
50 result += log(n - k + i) - log(i);
51 }
52 return result;
53 }
54}
55} // namespace operations_research
static double Stirling(double n)
Definition mathutil.cc:26
static double LogCombinations(int n, int k)
Definition mathutil.cc:33
In SWIG mode, we don't want anything besides these top-level includes.