pairinteraction
A Rydberg Interaction Calculator
maths.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2024 Pairinteraction Developers
2// SPDX-License-Identifier: LGPL-3.0-or-later
3
4#pragma once
5
6#include <stdexcept>
7#include <type_traits>
8
10
11template <typename Real>
12inline Real binomial_coefficient(Real n, Real k) {
13 static_assert(std::is_arithmetic_v<Real>);
14
15 if (n < k || k < 0) {
16 throw std::invalid_argument("It must be n >= k >= 0.");
17 }
18 if (k == 0) {
19 return 1;
20 }
21
22 // Recursion (n, k) = (n - 1, k - 1) * n / k
23 Real result = n - k + 1;
24 for (int i = 1; i < k; ++i) {
25 result *= (n - k + 1 + i) / (i + 1);
26 }
27
28 return result;
29}
30
31template <typename Real>
32inline Real factorial(Real n) {
33 static_assert(std::is_arithmetic_v<Real>);
34
35 if (n < 0) {
36 throw std::invalid_argument("It must be n >= 0.");
37 }
38 if (n == 0) {
39 return 1;
40 }
41
42 Real result = 1;
43 for (int i = 2; i <= n; ++i) {
44 result *= i;
45 }
46
47 return result;
48}
49
50} // namespace pairinteraction::maths
Real binomial_coefficient(Real n, Real k)
Definition: maths.hpp:12
Real factorial(Real n)
Definition: maths.hpp:32