-
Notifications
You must be signed in to change notification settings - Fork 2
/
logdouble.hpp
79 lines (67 loc) · 1.73 KB
/
logdouble.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#ifndef LOG_DOUBLE
#define LOG_DOUBLE
#include <cmath>
#include <algorithm>
#include <iostream>
#include <limits>
using std::min;
using std::max;
using std::isinf;
class logdouble {
public:
double logval;
logdouble() : logval(-std::numeric_limits<double>::infinity()) {}
logdouble(double x) : logval(log(x)) {}
logdouble operator+=(const logdouble &b) {
if (isinf(logval) && logval < 0) {
logval = b.logval;
return *this;
}
if (isinf(b.logval) && b.logval < 0) {
return *this;
}
logval = max(logval, b.logval) + log1p(exp(min(logval, b.logval) - max(logval, b.logval)));
return *this;
}
logdouble operator*=(const logdouble &b) {
logval += b.logval;
return *this;
}
};
inline logdouble operator+(const logdouble& a, const logdouble& b) {
if (isinf(a.logval) && a.logval < 0) {
return b;
}
if (isinf(b.logval) && b.logval < 0) {
return a;
}
logdouble ret;
ret.logval = max(a.logval, b.logval) + log1p(exp(min(a.logval, b.logval) - max(a.logval, b.logval)));
return ret;
}
inline logdouble operator*(const logdouble& a, const logdouble& b) {
logdouble ret;
ret.logval = a.logval + b.logval;
return ret;
}
inline logdouble operator^(const logdouble& a, const double& b) {
logdouble ret;
ret.logval = a.logval * b;
return ret;
}
inline logdouble operator/(const logdouble& a, const logdouble& b) {
logdouble ret;
ret.logval = a.logval - b.logval;
return ret;
}
inline std::ostream& operator<<(std::ostream& os, logdouble l) {
os << l.logval;
return os;
}
inline bool operator<(const logdouble& a, const logdouble& b) {
return a.logval < b.logval;
}
inline bool operator>(const logdouble& a, const logdouble& b) {
return a.logval > b.logval;
}
#endif