Add loadsvg script command, fix ParanoidNumber size limiting*
[ipdf/code.git] / src / paranoidnumber.h
1 #ifndef _PARANOIDNUMBER_H
2 #define _PARANOIDNUMBER_H
3
4 #include <list>
5 #include <cfloat>
6 #include <map>
7 #include <string>
8 #include "log.h"
9 #include <fenv.h>
10 #include <vector>
11 #include <cmath>
12 #include <cassert> // it's going to be ok
13 #include <set>
14
15 #define PARANOID_DIGIT_T double // we could theoretically replace this with a template
16                                                                 // but let's not do that...
17                                                                 
18
19 //#define PARANOID_CACHE_RESULTS
20
21 //#define PARANOID_USE_ARENA
22 #define PARANOID_SIZE_LIMIT 1
23
24
25 // Define to compare all ops against double ops and check within epsilon
26 #define PARANOID_COMPARE_EPSILON 1e-6
27 #define CompareForSanity(...) ParanoidNumber::CompareForSanityEx(__func__, __FILE__, __LINE__, __VA_ARGS__)
28
29 namespace IPDF
30 {
31         typedef enum {ADD, SUBTRACT, MULTIPLY, DIVIDE, NOP} Optype;
32         inline Optype InverseOp(Optype op)
33         {
34                 return ((op == ADD) ? SUBTRACT :
35                                 (op == SUBTRACT) ? ADD :
36                                 (op == MULTIPLY) ? DIVIDE :
37                                 (op == DIVIDE) ? MULTIPLY :
38                                 (op == NOP) ? NOP : NOP);
39         }
40         
41
42         inline char OpChar(int op) 
43         {
44                 static char opch[] = {'+','-','*','/'};
45                 return (op < NOP && op >= 0) ? opch[op] : '?';
46         }
47         
48
49         /** Performs an operation, returning if the result was exact **/
50         // NOTE: DIFFERENT to ParanoidOp (although that wraps to this...)
51         template <class T> bool TrustingOp(T & a, const T & b, Optype op);
52
53         /** Performs an operation _only_ if the result would be exact **/
54         template <class T> bool ParanoidOp(T & a, const T & b, Optype op)
55         {
56                 T cpy(a);
57                 if (TrustingOp<T>(cpy, b, op))
58                 {
59                         a = cpy;
60                         return true;
61                 }
62                 return false;
63         }
64         template <> bool TrustingOp<float>(float & a, const float & b, Optype op);
65         template <> bool TrustingOp<double>(double & a, const double & b, Optype op);
66         template <> bool TrustingOp<int8_t>(int8_t & a, const int8_t & b, Optype op);
67         
68         /**
69          * A ParanoidNumber
70          * Idea: Perform regular floating point arithmetic but rearrange operations to only ever use exact results
71          * Memory Usage: O(all of it)
72          * CPU Usage: O(all of it)
73          * Accuracy: O(gives better result for 0.3+0.3+0.3, gives same result for everything else, or worse result)
74          * 
75          * The ParanoidNumber basically stores 4 linked lists which can be split into two "dimensions"
76          *  1. Terms to ADD and terms to SUBTRACT
77          *  2. Factors to MULTIPLY and DIVIDE
78          * Because ADD and SUBTRACT are inverse operations and MULTIPLY and DIVIDE are inverse operations
79          * See paranoidnumber.cpp and the ParanoidNumber::Operation function
80          */
81         class ParanoidNumber
82         {
83                 
84                 public:
85                         typedef PARANOID_DIGIT_T digit_t;
86
87                         ParanoidNumber(PARANOID_DIGIT_T value=0) : m_value(value), m_next()
88                         {
89                                 #ifdef PARANOID_SIZE_LIMIT
90                                         m_size = 1;
91                                 #endif
92                                 #ifdef PARANOID_CACHE_RESULTS
93                                         m_cached_result = value;
94                                 #endif 
95                         }
96                         
97                         ParanoidNumber(const ParanoidNumber & cpy) : m_value(cpy.m_value), m_next()
98                         {
99                                 
100                                 #ifdef PARANOID_SIZE_LIMIT
101                                         m_size = cpy.m_size;
102                                 #endif
103                                 #ifdef PARANOID_CACHE_RESULTS
104                                         m_cached_result = cpy.m_cached_result;
105                                 #endif 
106                                 for (int i = 0; i < NOP; ++i)
107                                 {
108                                         for (auto next : cpy.m_next[i])
109                                         {
110                                                 if (next != NULL) // why would this ever be null
111                                                         m_next[i].push_back(new ParanoidNumber(*next)); // famous last words...
112                                         }
113                                 }
114                                 #ifdef PARANOID_COMPARE_EPSILON
115                                         CompareForSanity(cpy.Digit(), cpy.Digit());
116                                 #endif
117                                 //assert(SanityCheck());
118                         }
119                         
120                         //ParanoidNumber(const char * str);
121                         ParanoidNumber(const std::string & str);// : ParanoidNumber(str.c_str()) {}
122                         
123                         virtual ~ParanoidNumber();
124
125                         
126                         bool SanityCheck(std::set<ParanoidNumber*> & visited) const;
127                         bool SanityCheck() const 
128                         {
129                                 std::set<ParanoidNumber*> s; 
130                                 return SanityCheck(s);
131                         }
132                         
133                         template <class T> T Convert() const;
134                         digit_t GetFactors() const;
135                         digit_t GetTerms() const;
136                 
137                         // This function is declared const purely to trick the compiler.
138                         // It is not actually const, and therefore, none of the other functions that call it are const either.
139                         digit_t Digit() const;
140                         
141                         // Like this one. It isn't const.
142                         double ToDouble() const {return (double)Digit();}
143                         
144                         // This one is probably const.
145                         bool Floating() const 
146                         {
147                                 return NoFactors() && NoTerms();
148                         }
149                         bool Sunken() const {return !Floating();} // I could not resist...
150                         
151                         bool NoFactors() const {return (m_next[MULTIPLY].size() == 0 && m_next[DIVIDE].size() == 0);}
152                         bool NoTerms() const {return (m_next[ADD].size() == 0 && m_next[SUBTRACT].size() == 0);}
153                         
154                         
155                         ParanoidNumber & operator+=(const ParanoidNumber & a);
156                         ParanoidNumber & operator-=(const ParanoidNumber & a);
157                         ParanoidNumber & operator*=(const ParanoidNumber & a);
158                         ParanoidNumber & operator/=(const ParanoidNumber & a);
159                         ParanoidNumber & operator=(const ParanoidNumber & a);
160                         
161                         ParanoidNumber & operator+=(const digit_t & a);
162                         ParanoidNumber & operator-=(const digit_t & a);
163                         ParanoidNumber & operator*=(const digit_t & a);
164                         ParanoidNumber & operator/=(const digit_t & a);
165                         ParanoidNumber & operator=(const digit_t & a);
166                         
167                         
168                         ParanoidNumber * OperationTerm(ParanoidNumber * b, Optype op, ParanoidNumber ** merge_point = NULL, Optype * mop = NULL);
169                         ParanoidNumber * OperationFactor(ParanoidNumber * b, Optype op, ParanoidNumber ** merge_point = NULL, Optype * mop = NULL);
170                         ParanoidNumber * TrivialOp(ParanoidNumber * b, Optype op);
171                         ParanoidNumber * Operation(ParanoidNumber * b, Optype op, ParanoidNumber ** merge_point = NULL, Optype * mop = NULL);
172                         bool Simplify(Optype op);
173                         bool FullSimplify();
174                         
175                         
176                         // None of these are actually const
177                         bool operator<(const ParanoidNumber & a) const {return Digit() < a.Digit();}
178                         bool operator<=(const ParanoidNumber & a) const {return Digit() <= a.Digit();}
179                         bool operator>(const ParanoidNumber & a) const {return Digit() > a.Digit();}
180                         bool operator>=(const ParanoidNumber & a) const {return Digit() >= a.Digit();}
181                         bool operator==(const ParanoidNumber & a) const {return Digit() == a.Digit();}
182                         bool operator!=(const ParanoidNumber & a) const {return Digit() != a.Digit();}
183                         
184                         ParanoidNumber operator-() const
185                         {
186                                 ParanoidNumber neg(*this);
187                                 neg.Negate();
188                                 #ifdef PARANOID_COMPARE_EPSILON
189                                         neg.CompareForSanity(-Digit(), Digit());
190                                 #endif
191                                 return neg;
192                         }
193                         
194                         void Negate();
195                         
196                         
197                         ParanoidNumber operator+(const ParanoidNumber & a) const
198                         {
199                                 ParanoidNumber result(*this);
200                                 result += a;
201                                 #ifdef PARANOID_COMPARE_EPSILON
202                                         result.CompareForSanity(Digit()+a.Digit(), a.Digit());
203                                 #endif
204                                 return result;
205                         }
206                         ParanoidNumber operator-(const ParanoidNumber & a) const
207                         {
208                                 ParanoidNumber result(*this);
209                                 result -= a;
210                                 #ifdef PARANOID_COMPARE_EPSILON
211                                         result.CompareForSanity(Digit()-a.Digit(), a.Digit());
212                                 #endif
213                                 return result;
214                         }
215                         ParanoidNumber operator*(const ParanoidNumber & a) const
216                         {
217                                 ParanoidNumber result(*this);
218                                 result *= a;
219                                 #ifdef PARANOID_COMPARE_EPSILON
220                                         result.CompareForSanity(Digit()*a.Digit(), a.Digit());
221                                 #endif
222                                 return result;
223                         }
224                         ParanoidNumber operator/(const ParanoidNumber & a) const
225                         {
226                                 ParanoidNumber result(*this);
227                                 result /= a;
228                                 #ifdef PARANOID_COMPARE_EPSILON
229                                         result.CompareForSanity(Digit()/a.Digit(), a.Digit());
230                                 #endif
231                                 return result;
232                         }
233                         
234                         std::string Str() const;
235
236                         inline void CompareForSanityEx(const char * func, const char * file, int line, const digit_t & compare, const digit_t & arg, const digit_t & eps = PARANOID_COMPARE_EPSILON)
237                         {
238                                 if (!SanityCheck())
239                                         Fatal("This is insane!");
240                                 if (fabs(Digit() - compare) > eps)
241                                 {
242                                         Error("Called via %s(%lf) (%s:%d)", func, arg, file, line);
243                                         Error("Failed: %s", Str().c_str());
244                                         Fatal("This: %.30lf vs Expected: %.30lf", Digit(), compare);
245                                 }
246                         }
247
248                         
249                         std::string PStr() const;
250                         
251                         #ifdef PARANOID_USE_ARENA
252                         void * operator new(size_t byes);
253                         void operator delete(void * p);
254                         #endif //PARANOID_USE_ARENA
255                 
256                 private:
257                 
258                         void Simplify();
259                         void SimplifyTerms();
260                         void SimplifyFactors();
261                         
262                         digit_t m_value;        
263                         #ifdef PARANOID_CACHE_RESULTS
264                                 digit_t m_cached_result;
265                         #endif
266                         std::vector<ParanoidNumber*> m_next[4];
267                         #ifdef PARANOID_SIZE_LIMIT
268                                 int64_t m_size;
269                         #endif //PARANOID_SIZE_LIMIT
270                         
271                         #ifdef PARANOID_USE_ARENA
272                         class Arena
273                         {
274                                 public:
275                                         Arena(int64_t block_size = 10000000);
276                                         ~Arena();
277                                         
278                                         void * allocate(size_t bytes);
279                                         void deallocate(void * p);
280                                         
281                                 private:
282                                         struct Block
283                                         {
284                                                 void * memory;
285                                                 int64_t used;
286                                         };
287                                 
288                                         std::vector<Block> m_blocks;
289                                         int64_t m_block_size;
290                                         
291                                         void * m_spare;
292                                 
293                         };
294                         
295                         static Arena g_arena;
296                         #endif //PARANOID_USE_ARENA
297
298                 
299         };
300         
301
302
303
304 template <class T>
305 T ParanoidNumber::Convert() const
306 {
307         #ifdef PARANOID_CACHE_RESULTS
308         if (!isnan((float(m_cached_result))))
309                 return (T)m_cached_result;
310         #endif
311         T value(m_value);
312         for (auto mul : m_next[MULTIPLY])
313         {
314                 value *= mul->Convert<T>();
315         }
316         for (auto div : m_next[DIVIDE])
317         {
318                 value /= div->Convert<T>();
319         }
320         for (auto add : m_next[ADD])
321                 value += add->Convert<T>();
322         for (auto sub : m_next[SUBTRACT])
323                 value -= sub->Convert<T>();
324         return value;
325 }
326
327
328
329 }
330
331 #endif //_PARANOIDNUMBER_H
332

UCC git Repository :: git.ucc.asn.au