File indexing completed on 2026-12-04 10:45:23
0001
0002
0003
0004
0005
0006
0007 #pragma once
0008
0009 #include <cmath>
0010 #include <type_traits>
0011
0012 #include "corecel/Config.hh"
0013
0014 #include "corecel/Assert.hh"
0015 #include "corecel/Macros.hh"
0016 #include "corecel/Types.hh"
0017
0018 #include "Algorithms.hh"
0019
0020 namespace celeritas
0021 {
0022
0023
0024
0025
0026
0027
0028
0029
0030
0031
0032
0033
0034
0035 template<class F>
0036 class IllinoisRootFinder
0037 {
0038 public:
0039
0040 inline CELER_FUNCTION IllinoisRootFinder(F&& func, real_type tol);
0041
0042
0043 inline CELER_FUNCTION real_type operator()(real_type left, real_type right);
0044
0045 private:
0046 F func_;
0047 real_type tol_;
0048
0049
0050 static constexpr int max_iters_ = 50;
0051 };
0052
0053
0054
0055
0056
0057 template<class F, class... Args>
0058 CELER_CTAD_FUNCTION IllinoisRootFinder(F&&, Args...) -> IllinoisRootFinder<F>;
0059
0060
0061
0062
0063
0064
0065
0066 template<class F>
0067 CELER_FUNCTION IllinoisRootFinder<F>::IllinoisRootFinder(F&& func,
0068 real_type tol)
0069 : func_{celeritas::forward<F>(func)}, tol_{tol}
0070 {
0071 CELER_EXPECT(tol_ > 0);
0072 }
0073
0074
0075
0076
0077
0078
0079
0080 template<class F>
0081 CELER_FUNCTION real_type IllinoisRootFinder<F>::operator()(real_type xl,
0082 real_type xr)
0083 {
0084 using namespace celeritas::literals;
0085
0086
0087 enum class Side
0088 {
0089 left = -1,
0090 init = 0,
0091 right = 1
0092 };
0093
0094
0095 real_type fl = func_(xl);
0096 real_type fr = func_(xr);
0097 real_type fx = 1;
0098 real_type x = 0;
0099 Side side = Side::init;
0100 int remaining_iters = max_iters_;
0101
0102
0103 do
0104 {
0105
0106 x = (xl * fr - xr * fl) / (fr - fl);
0107 fx = func_(x);
0108
0109
0110 if (signum(fl) == signum(fx))
0111 {
0112 xl = x;
0113 fl = fx;
0114 if (side == Side::left)
0115 {
0116 fr *= 0.5_r;
0117 }
0118 side = Side::left;
0119 }
0120 else
0121 {
0122 xr = x;
0123 fr = fx;
0124 if (side == Side::right)
0125 {
0126 fl *= 0.5_r;
0127 }
0128 side = Side::right;
0129 }
0130 } while (std::fabs(fx) > tol_ && --remaining_iters > 0);
0131
0132 CELER_ENSURE(remaining_iters > 0);
0133 return x;
0134 }
0135
0136
0137 }