ABACUS develop
Atomic-orbital Based Ab-initio Computation at UStc
Loading...
Searching...
No Matches
truncated_func.h
Go to the documentation of this file.
1#ifndef MODULE_BASE_TRUNCATED_FUNC_H
2#define MODULE_BASE_TRUNCATED_FUNC_H
3
5#include <cstdint>
6#include <cstring>
7#include <complex>
8
9namespace ModuleBase
10{
11
22template <typename FPTYPE>
23inline FPTYPE truncated_exp(FPTYPE x)
24{
25 if (std::real(x) < -230.0)
26 {
27 return static_cast<FPTYPE>(0.0);
28 }
29 return ModuleBase::libm::exp(x);
30}
31
42template <typename FPTYPE>
43inline FPTYPE truncated_erfc(FPTYPE x)
44{
45 if (std::real(x) > 20.0)
46 {
47 return static_cast<FPTYPE>(0.0);
48 }
49 return std::erfc(x);
50}
51
70template <typename FPTYPE>
71inline void truncated_underflow(FPTYPE& x)
72{
73 if (std::abs(x) < 1.0e-30)
74 {
75 x = static_cast<FPTYPE>(0.0);
76 }
77}
78
79template <>
80inline void truncated_underflow(double& x)
81{
82 const uint64_t u = *reinterpret_cast<const uint64_t*>(&x);
83 // The exponent bits are 52-62 (11 bits). The bias is 1023.
84 // 1e-30 corresponds to -100 in base-2 exponent roughly.
85 // 923 = 1023 - 100.
86 if (((u >> 52) & 0x7FF) <= 923)
87 {
88 x = 0.0;
89 }
90}
91
92template <>
93inline void truncated_underflow(float& x)
94{
95 const uint32_t u = *reinterpret_cast<const uint32_t*>(&x);
96 // The exponent bits are 23-30 (8 bits). The bias is 127.
97 // 1e-30 corresponds to -100 in base-2 exponent roughly.
98 // 27 = 127 - 100.
99 if (((u >> 23) & 0xFF) <= 27)
100 {
101 x = 0.0f;
102 }
103}
104
105template <typename T>
106inline void truncated_underflow(std::complex<T>& x)
107{
108 T* ptr = reinterpret_cast<T*>(&x);
109 truncated_underflow(ptr[0]);
110 truncated_underflow(ptr[1]);
111}
112
113
114} // namespace ModuleBase
115
116#endif // MODULE_BASE_TRUNCATED_FUNC_H
#define T
Definition exp.cpp:237
Definition clebsch_gordan_coeff.cpp:8
FPTYPE truncated_erfc(FPTYPE x)
Truncated complementary error function to avoid underflow for large arguments.
Definition truncated_func.h:43
void truncated_underflow(FPTYPE &x)
Truncated value function to avoid underflow.
Definition truncated_func.h:71
FPTYPE truncated_exp(FPTYPE x)
Truncated exponential function to avoid underflow.
Definition truncated_func.h:23