Uni20
Asynchronous tensor and runtime library.
Loading...
Searching...
No Matches
factorial.hpp
Go to the documentation of this file.
1#pragma once
2
5#if UNI20_HAS_MPREAL
6#include "mpreal.hpp"
7#endif
8
9namespace uni20
10{
15template <detail::native_math::NativeReal R, detail::MathInteger I> R factorial(I n)
16{
17 auto order = detail::math_integer(n);
18 if (order < 0) throw std::domain_error("factorial requires a nonnegative order");
19 using L = numeric_limits<R>;
20 if (order > L::max_exponent) return L::infinity(); // n! >= 2^(n-1).
21 R high = 1, low = 0;
22 for (std::int64_t k = 2; k <= order; ++k)
23 {
24 R factor = R(k);
25 R product = high * factor;
26 if (std::isinf(product)) return product;
27 // Recover the high product's rounding residual and propagate the low word.
28 // FastTwoSum renormalizes the much smaller correction into a new low word.
29 R error = std::fma(high, factor, -product) + low * factor;
30 R sum = product + error;
31 low = error - (sum - product);
32 high = sum;
33 }
34 return high;
35}
36
39template <detail::native_math::NativeReal R, detail::MathInteger I> R factorial(I n, Precision p)
40{
41 require_precision<R>(p);
42 return uni20::factorial<R>(n);
43}
44
45#if UNI20_HAS_MPREAL
49template <class R, detail::MathInteger I>
50 requires std::same_as<R, mpreal>
51R factorial(I n, Precision p)
52{
53 return uni20::factorial(n, p);
54}
55#endif
56} // namespace uni20
Exact arithmetic or an explicit binary working precision.
Definition core/precision.hpp:13
T product(std::vector< T > const &values)
Definition mpreal_exact_example.cpp:13
Definition data_table.cpp:8
Definition async/async.hpp:26
void sum(BackendSelector selector, async::Async< OutputTensor > &output, async::Async< InputTensor > const &input)
Schedule a full sum into an explicit async scalar tensor.
Definition linalg/async/reductions.hpp:309
R factorial(I n)
Factorial of a checked nonnegative integer, with an explicit native result type.
Definition factorial.hpp:15
Project-level numeric limits customization point.
Definition numeric_limits.hpp:16