gravatar
alpar (Alpar Juttner)
alpar@cs.elte.hu
Merge
0 7 3
merge default
0 files changed with 1083 insertions and 111 deletions:
↑ Collapse diff ↑
Ignore white space 6 line context
1
/* -*- C++ -*-
2
 *
3
 * This file is a part of LEMON, a generic C++ optimization library
4
 *
5
 * Copyright (C) 2003-2007
6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8
 *
9
 * Permission to use, modify and distribute this software is granted
10
 * provided that this copyright notice appears in all copies. For
11
 * precise terms see the accompanying LICENSE file.
12
 *
13
 * This software is provided "AS IS" with no warranty of any kind,
14
 * express or implied, and with no claim as to its suitability for any
15
 * purpose.
16
 *
17
 */
18

	
19
///\file
20
///\brief Instantiation of the Random class.
21

	
22
#include <lemon/random.h>
23

	
24
namespace lemon {
25
  /// \brief Global random number generator instance
26
  ///
27
  /// A global Mersenne Twister random number generator instance.
28
  Random rnd;
29
}
Ignore white space 6 line context
1
/* -*- C++ -*-
2
 *
3
 * This file is a part of LEMON, a generic C++ optimization library
4
 *
5
 * Copyright (C) 2003-2007
6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8
 *
9
 * Permission to use, modify and distribute this software is granted
10
 * provided that this copyright notice appears in all copies. For
11
 * precise terms see the accompanying LICENSE file.
12
 *
13
 * This software is provided "AS IS" with no warranty of any kind,
14
 * express or implied, and with no claim as to its suitability for any
15
 * purpose.
16
 *
17
 */
18

	
19
/*
20
 * This file contains the reimplemented version of the Mersenne Twister
21
 * Generator of Matsumoto and Nishimura.
22
 *
23
 * See the appropriate copyright notice below.
24
 * 
25
 * Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
26
 * All rights reserved.                          
27
 *
28
 * Redistribution and use in source and binary forms, with or without
29
 * modification, are permitted provided that the following conditions
30
 * are met:
31
 *
32
 * 1. Redistributions of source code must retain the above copyright
33
 *    notice, this list of conditions and the following disclaimer.
34
 *
35
 * 2. Redistributions in binary form must reproduce the above copyright
36
 *    notice, this list of conditions and the following disclaimer in the
37
 *    documentation and/or other materials provided with the distribution.
38
 *
39
 * 3. The names of its contributors may not be used to endorse or promote 
40
 *    products derived from this software without specific prior written 
41
 *    permission.
42
 *
43
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
44
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
45
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
46
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
47
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
48
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
49
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
50
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
52
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
53
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
54
 * OF THE POSSIBILITY OF SUCH DAMAGE.
55
 *
56
 *
57
 * Any feedback is very welcome.
58
 * http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
59
 * email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
60
 */
61

	
62
#ifndef LEMON_RANDOM_H
63
#define LEMON_RANDOM_H
64

	
65
#include <algorithm>
66
#include <iterator>
67
#include <vector>
68

	
69
#include <ctime>
70
#include <cmath>
71

	
72
#include <lemon/dim2.h>
73
///\ingroup misc
74
///\file
75
///\brief Mersenne Twister random number generator
76

	
77
namespace lemon {
78

	
79
  namespace _random_bits {
80
    
81
    template <typename _Word, int _bits = std::numeric_limits<_Word>::digits>
82
    struct RandomTraits {};
83

	
84
    template <typename _Word>
85
    struct RandomTraits<_Word, 32> {
86

	
87
      typedef _Word Word;
88
      static const int bits = 32;
89

	
90
      static const int length = 624;
91
      static const int shift = 397;
92
      
93
      static const Word mul = 0x6c078965u;
94
      static const Word arrayInit = 0x012BD6AAu;
95
      static const Word arrayMul1 = 0x0019660Du;
96
      static const Word arrayMul2 = 0x5D588B65u;
97

	
98
      static const Word mask = 0x9908B0DFu;
99
      static const Word loMask = (1u << 31) - 1;
100
      static const Word hiMask = ~loMask;
101

	
102

	
103
      static Word tempering(Word rnd) {
104
        rnd ^= (rnd >> 11);
105
        rnd ^= (rnd << 7) & 0x9D2C5680u;
106
        rnd ^= (rnd << 15) & 0xEFC60000u;
107
        rnd ^= (rnd >> 18);
108
        return rnd;
109
      }
110

	
111
    };
112

	
113
    template <typename _Word>
114
    struct RandomTraits<_Word, 64> {
115

	
116
      typedef _Word Word;
117
      static const int bits = 64;
118

	
119
      static const int length = 312;
120
      static const int shift = 156;
121

	
122
      static const Word mul = Word(0x5851F42Du) << 32 | Word(0x4C957F2Du);
123
      static const Word arrayInit = Word(0x00000000u) << 32 |Word(0x012BD6AAu);
124
      static const Word arrayMul1 = Word(0x369DEA0Fu) << 32 |Word(0x31A53F85u);
125
      static const Word arrayMul2 = Word(0x27BB2EE6u) << 32 |Word(0x87B0B0FDu);
126

	
127
      static const Word mask = Word(0xB5026F5Au) << 32 | Word(0xA96619E9u);
128
      static const Word loMask = (Word(1u) << 31) - 1;
129
      static const Word hiMask = ~loMask;
130

	
131
      static Word tempering(Word rnd) {
132
        rnd ^= (rnd >> 29) & (Word(0x55555555u) << 32 | Word(0x55555555u));
133
        rnd ^= (rnd << 17) & (Word(0x71D67FFFu) << 32 | Word(0xEDA60000u));
134
        rnd ^= (rnd << 37) & (Word(0xFFF7EEE0u) << 32 | Word(0x00000000u));
135
        rnd ^= (rnd >> 43);
136
        return rnd;
137
      }
138

	
139
    };
140

	
141
    template <typename _Word>
142
    class RandomCore {
143
    public:
144

	
145
      typedef _Word Word;
146

	
147
    private:
148

	
149
      static const int bits = RandomTraits<Word>::bits;
150

	
151
      static const int length = RandomTraits<Word>::length;
152
      static const int shift = RandomTraits<Word>::shift;
153

	
154
    public:
155

	
156
      void initState() {
157
        static const Word seedArray[4] = {
158
          0x12345u, 0x23456u, 0x34567u, 0x45678u
159
        };
160
    
161
        initState(seedArray, seedArray + 4);
162
      }
163

	
164
      void initState(Word seed) {
165

	
166
        static const Word mul = RandomTraits<Word>::mul;
167

	
168
        current = state; 
169

	
170
        Word *curr = state + length - 1;
171
        curr[0] = seed; --curr;
172
        for (int i = 1; i < length; ++i) {
173
          curr[0] = (mul * ( curr[1] ^ (curr[1] >> (bits - 2)) ) + i);
174
          --curr;
175
        }
176
      }
177

	
178
      template <typename Iterator>
179
      void initState(Iterator begin, Iterator end) {
180

	
181
        static const Word init = RandomTraits<Word>::arrayInit;
182
        static const Word mul1 = RandomTraits<Word>::arrayMul1;
183
        static const Word mul2 = RandomTraits<Word>::arrayMul2;
184

	
185

	
186
        Word *curr = state + length - 1; --curr;
187
        Iterator it = begin; int cnt = 0;
188
        int num;
189

	
190
        initState(init);
191

	
192
        num = length > end - begin ? length : end - begin;
193
        while (num--) {
194
          curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul1)) 
195
            + *it + cnt;
196
          ++it; ++cnt;
197
          if (it == end) {
198
            it = begin; cnt = 0;
199
          }
200
          if (curr == state) {
201
            curr = state + length - 1; curr[0] = state[0];
202
          }
203
          --curr;
204
        }
205

	
206
        num = length - 1; cnt = length - (curr - state) - 1;
207
        while (num--) {
208
          curr[0] = (curr[0] ^ ((curr[1] ^ (curr[1] >> (bits - 2))) * mul2))
209
            - cnt;
210
          --curr; ++cnt;
211
          if (curr == state) {
212
            curr = state + length - 1; curr[0] = state[0]; --curr;
213
            cnt = 1;
214
          }
215
        }
216
        
217
        state[length - 1] = Word(1) << (bits - 1);
218
      }
219
      
220
      void copyState(const RandomCore& other) {
221
        std::copy(other.state, other.state + length, state);
222
        current = state + (other.current - other.state);
223
      }
224

	
225
      Word operator()() {
226
        if (current == state) fillState();
227
        --current;
228
        Word rnd = *current;
229
        return RandomTraits<Word>::tempering(rnd);
230
      }
231

	
232
    private:
233

	
234
  
235
      void fillState() {
236
        static const Word mask[2] = { 0x0ul, RandomTraits<Word>::mask };
237
        static const Word loMask = RandomTraits<Word>::loMask;
238
        static const Word hiMask = RandomTraits<Word>::hiMask;
239

	
240
        current = state + length; 
241

	
242
        register Word *curr = state + length - 1;
243
        register long num;
244
      
245
        num = length - shift;
246
        while (num--) {
247
          curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
248
            curr[- shift] ^ mask[curr[-1] & 1ul];
249
          --curr;
250
        }
251
        num = shift - 1;
252
        while (num--) {
253
          curr[0] = (((curr[0] & hiMask) | (curr[-1] & loMask)) >> 1) ^
254
            curr[length - shift] ^ mask[curr[-1] & 1ul];
255
          --curr;
256
        }
257
        curr[0] = (((curr[0] & hiMask) | (curr[length - 1] & loMask)) >> 1) ^
258
          curr[length - shift] ^ mask[curr[length - 1] & 1ul];
259

	
260
      }
261

	
262
  
263
      Word *current;
264
      Word state[length];
265
      
266
    };
267

	
268

	
269
    template <typename Result, 
270
              int shift = (std::numeric_limits<Result>::digits + 1) / 2>
271
    struct Masker {
272
      static Result mask(const Result& result) {
273
        return Masker<Result, (shift + 1) / 2>::
274
          mask(static_cast<Result>(result | (result >> shift)));
275
      }
276
    };
277
    
278
    template <typename Result>
279
    struct Masker<Result, 1> {
280
      static Result mask(const Result& result) {
281
        return static_cast<Result>(result | (result >> 1));
282
      }
283
    };
284

	
285
    template <typename Result, typename Word, 
286
              int rest = std::numeric_limits<Result>::digits, int shift = 0, 
287
              bool last = rest <= std::numeric_limits<Word>::digits>
288
    struct IntConversion {
289
      static const int bits = std::numeric_limits<Word>::digits;
290
    
291
      static Result convert(RandomCore<Word>& rnd) {
292
        return static_cast<Result>(rnd() >> (bits - rest)) << shift;
293
      }
294
      
295
    }; 
296

	
297
    template <typename Result, typename Word, int rest, int shift> 
298
    struct IntConversion<Result, Word, rest, shift, false> {
299
      static const int bits = std::numeric_limits<Word>::digits;
300

	
301
      static Result convert(RandomCore<Word>& rnd) {
302
        return (static_cast<Result>(rnd()) << shift) | 
303
          IntConversion<Result, Word, rest - bits, shift + bits>::convert(rnd);
304
      }
305
    };
306

	
307

	
308
    template <typename Result, typename Word,
309
              bool one_word = (std::numeric_limits<Word>::digits < 
310
			       std::numeric_limits<Result>::digits) >
311
    struct Mapping {
312
      static Result map(RandomCore<Word>& rnd, const Result& bound) {
313
        Word max = Word(bound - 1);
314
        Result mask = Masker<Result>::mask(bound - 1);
315
        Result num;
316
        do {
317
          num = IntConversion<Result, Word>::convert(rnd) & mask; 
318
        } while (num > max);
319
        return num;
320
      }
321
    };
322

	
323
    template <typename Result, typename Word>
324
    struct Mapping<Result, Word, false> {
325
      static Result map(RandomCore<Word>& rnd, const Result& bound) {
326
        Word max = Word(bound - 1);
327
        Word mask = Masker<Word, (std::numeric_limits<Result>::digits + 1) / 2>
328
          ::mask(max);
329
        Word num;
330
        do {
331
          num = rnd() & mask;
332
        } while (num > max);
333
        return num;
334
      }
335
    };
336

	
337
    template <typename Result, int exp, bool pos = (exp >= 0)>
338
    struct ShiftMultiplier {
339
      static const Result multiplier() {
340
        Result res = ShiftMultiplier<Result, exp / 2>::multiplier();
341
        res *= res;
342
        if ((exp & 1) == 1) res *= static_cast<Result>(2.0);
343
        return res; 
344
      }
345
    };
346

	
347
    template <typename Result, int exp>
348
    struct ShiftMultiplier<Result, exp, false> {
349
      static const Result multiplier() {
350
        Result res = ShiftMultiplier<Result, exp / 2>::multiplier();
351
        res *= res;
352
        if ((exp & 1) == 1) res *= static_cast<Result>(0.5);
353
        return res; 
354
      }
355
    };
356

	
357
    template <typename Result>
358
    struct ShiftMultiplier<Result, 0, true> {
359
      static const Result multiplier() {
360
        return static_cast<Result>(1.0); 
361
      }
362
    };
363

	
364
    template <typename Result>
365
    struct ShiftMultiplier<Result, -20, true> {
366
      static const Result multiplier() {
367
        return static_cast<Result>(1.0/1048576.0); 
368
      }
369
    };
370
    
371
    template <typename Result>
372
    struct ShiftMultiplier<Result, -32, true> {
373
      static const Result multiplier() {
374
        return static_cast<Result>(1.0/424967296.0); 
375
      }
376
    };
377

	
378
    template <typename Result>
379
    struct ShiftMultiplier<Result, -53, true> {
380
      static const Result multiplier() {
381
        return static_cast<Result>(1.0/9007199254740992.0); 
382
      }
383
    };
384

	
385
    template <typename Result>
386
    struct ShiftMultiplier<Result, -64, true> {
387
      static const Result multiplier() {
388
        return static_cast<Result>(1.0/18446744073709551616.0); 
389
      }
390
    };
391

	
392
    template <typename Result, int exp>
393
    struct Shifting {
394
      static Result shift(const Result& result) {
395
        return result * ShiftMultiplier<Result, exp>::multiplier();
396
      }
397
    };
398

	
399
    template <typename Result, typename Word,
400
              int rest = std::numeric_limits<Result>::digits, int shift = 0, 
401
              bool last = rest <= std::numeric_limits<Word>::digits>
402
    struct RealConversion{ 
403
      static const int bits = std::numeric_limits<Word>::digits;
404

	
405
      static Result convert(RandomCore<Word>& rnd) {
406
        return Shifting<Result, - shift - rest>::
407
          shift(static_cast<Result>(rnd() >> (bits - rest)));
408
      }
409
    };
410

	
411
    template <typename Result, typename Word, int rest, int shift>
412
    struct RealConversion<Result, Word, rest, shift, false> { 
413
      static const int bits = std::numeric_limits<Word>::digits;
414

	
415
      static Result convert(RandomCore<Word>& rnd) {
416
        return Shifting<Result, - shift - bits>::
417
          shift(static_cast<Result>(rnd())) +
418
          RealConversion<Result, Word, rest-bits, shift + bits>::
419
          convert(rnd);
420
      }
421
    };
422

	
423
    template <typename Result, typename Word>
424
    struct Initializer {
425

	
426
      template <typename Iterator>
427
      static void init(RandomCore<Word>& rnd, Iterator begin, Iterator end) {
428
        std::vector<Word> ws;
429
        for (Iterator it = begin; it != end; ++it) {
430
          ws.push_back(Word(*it));
431
        }
432
        rnd.initState(ws.begin(), ws.end());
433
      }
434

	
435
      static void init(RandomCore<Word>& rnd, Result seed) {
436
        rnd.initState(seed);
437
      }
438
    };
439

	
440
    template <typename Word>
441
    struct BoolConversion {
442
      static bool convert(RandomCore<Word>& rnd) {
443
        return (rnd() & 1) == 1;
444
      }
445
    };
446

	
447
    template <typename Word>
448
    struct BoolProducer {
449
      Word buffer;
450
      int num;
451
      
452
      BoolProducer() : num(0) {}
453

	
454
      bool convert(RandomCore<Word>& rnd) {
455
        if (num == 0) {
456
          buffer = rnd();
457
          num = RandomTraits<Word>::bits;
458
        }
459
        bool r = (buffer & 1);
460
        buffer >>= 1;
461
        --num;
462
        return r;
463
      }
464
    };
465

	
466
  }
467

	
468
  /// \ingroup misc
469
  ///
470
  /// \brief Mersenne Twister random number generator
471
  ///
472
  /// The Mersenne Twister is a twisted generalized feedback
473
  /// shift-register generator of Matsumoto and Nishimura. The period
474
  /// of this generator is \f$ 2^{19937} - 1 \f$ and it is
475
  /// equi-distributed in 623 dimensions for 32-bit numbers. The time
476
  /// performance of this generator is comparable to the commonly used
477
  /// generators.
478
  ///
479
  /// This implementation is specialized for both 32-bit and 64-bit
480
  /// architectures. The generators differ sligthly in the
481
  /// initialization and generation phase so they produce two
482
  /// completly different sequences.
483
  ///
484
  /// The generator gives back random numbers of serveral types. To
485
  /// get a random number from a range of a floating point type you
486
  /// can use one form of the \c operator() or the \c real() member
487
  /// function. If you want to get random number from the {0, 1, ...,
488
  /// n-1} integer range use the \c operator[] or the \c integer()
489
  /// method. And to get random number from the whole range of an
490
  /// integer type you can use the argumentless \c integer() or \c
491
  /// uinteger() functions. After all you can get random bool with
492
  /// equal chance of true and false or given probability of true
493
  /// result with the \c boolean() member functions.
494
  ///
495
  ///\code
496
  /// // The commented code is identical to the other
497
  /// double a = rnd();                     // [0.0, 1.0)
498
  /// // double a = rnd.real();             // [0.0, 1.0)
499
  /// double b = rnd(100.0);                // [0.0, 100.0)
500
  /// // double b = rnd.real(100.0);        // [0.0, 100.0)
501
  /// double c = rnd(1.0, 2.0);             // [1.0, 2.0)
502
  /// // double c = rnd.real(1.0, 2.0);     // [1.0, 2.0)
503
  /// int d = rnd[100000];                  // 0..99999
504
  /// // int d = rnd.integer(100000);       // 0..99999
505
  /// int e = rnd[6] + 1;                   // 1..6
506
  /// // int e = rnd.integer(1, 1 + 6);     // 1..6
507
  /// int b = rnd.uinteger<int>();          // 0 .. 2^31 - 1
508
  /// int c = rnd.integer<int>();           // - 2^31 .. 2^31 - 1
509
  /// bool g = rnd.boolean();               // P(g = true) = 0.5
510
  /// bool h = rnd.boolean(0.8);            // P(h = true) = 0.8
511
  ///\endcode
512
  ///
513
  /// The lemon provides a global instance of the random number
514
  /// generator which name is \ref lemon::rnd "rnd". Usually it is a
515
  /// good programming convenience to use this global generator to get
516
  /// random numbers.
517
  class Random {
518
  private:
519

	
520
    // Architecture word
521
    typedef unsigned long Word;
522
    
523
    _random_bits::RandomCore<Word> core;
524
    _random_bits::BoolProducer<Word> bool_producer;
525
    
526

	
527
  public:
528

	
529
    /// \brief Constructor
530
    ///
531
    /// Constructor with constant seeding.
532
    Random() { core.initState(); }
533

	
534
    /// \brief Constructor
535
    ///
536
    /// Constructor with seed. The current number type will be converted
537
    /// to the architecture word type.
538
    template <typename Number>
539
    Random(Number seed) { 
540
      _random_bits::Initializer<Number, Word>::init(core, seed);
541
    }
542

	
543
    /// \brief Constructor
544
    ///
545
    /// Constructor with array seeding. The given range should contain
546
    /// any number type and the numbers will be converted to the
547
    /// architecture word type.
548
    template <typename Iterator>
549
    Random(Iterator begin, Iterator end) { 
550
      typedef typename std::iterator_traits<Iterator>::value_type Number;
551
      _random_bits::Initializer<Number, Word>::init(core, begin, end);
552
    }
553

	
554
    /// \brief Copy constructor
555
    ///
556
    /// Copy constructor. The generated sequence will be identical to
557
    /// the other sequence. It can be used to save the current state
558
    /// of the generator and later use it to generate the same
559
    /// sequence.
560
    Random(const Random& other) {
561
      core.copyState(other.core);
562
    }
563

	
564
    /// \brief Assign operator
565
    ///
566
    /// Assign operator. The generated sequence will be identical to
567
    /// the other sequence. It can be used to save the current state
568
    /// of the generator and later use it to generate the same
569
    /// sequence.
570
    Random& operator=(const Random& other) {
571
      if (&other != this) {
572
        core.copyState(other.core);
573
      }
574
      return *this;
575
    }
576

	
577
    /// \brief Returns a random real number from the range [0, 1)
578
    ///
579
    /// It returns a random real number from the range [0, 1). The
580
    /// default Number type is double.
581
    template <typename Number>
582
    Number real() {
583
      return _random_bits::RealConversion<Number, Word>::convert(core);
584
    }
585

	
586
    double real() {
587
      return real<double>();
588
    }
589

	
590
    /// \brief Returns a random real number the range [0, b)
591
    ///
592
    /// It returns a random real number from the range [0, b).
593
    template <typename Number>
594
    Number real(Number b) { 
595
      return real<Number>() * b; 
596
    }
597

	
598
    /// \brief Returns a random real number from the range [a, b)
599
    ///
600
    /// It returns a random real number from the range [a, b).
601
    template <typename Number>
602
    Number real(Number a, Number b) { 
603
      return real<Number>() * (b - a) + a; 
604
    }
605

	
606
    /// \brief Returns a random real number from the range [0, 1)
607
    ///
608
    /// It returns a random double from the range [0, 1).
609
    double operator()() {
610
      return real<double>();
611
    }
612

	
613
    /// \brief Returns a random real number from the range [0, b)
614
    ///
615
    /// It returns a random real number from the range [0, b).
616
    template <typename Number>
617
    Number operator()(Number b) { 
618
      return real<Number>() * b; 
619
    }
620

	
621
    /// \brief Returns a random real number from the range [a, b)
622
    ///
623
    /// It returns a random real number from the range [a, b).
624
    template <typename Number>
625
    Number operator()(Number a, Number b) { 
626
      return real<Number>() * (b - a) + a; 
627
    }
628

	
629
    /// \brief Returns a random integer from a range
630
    ///
631
    /// It returns a random integer from the range {0, 1, ..., b - 1}.
632
    template <typename Number>
633
    Number integer(Number b) {
634
      return _random_bits::Mapping<Number, Word>::map(core, b);
635
    }
636

	
637
    /// \brief Returns a random integer from a range
638
    ///
639
    /// It returns a random integer from the range {a, a + 1, ..., b - 1}.
640
    template <typename Number>
641
    Number integer(Number a, Number b) {
642
      return _random_bits::Mapping<Number, Word>::map(core, b - a) + a;
643
    }
644

	
645
    /// \brief Returns a random integer from a range
646
    ///
647
    /// It returns a random integer from the range {0, 1, ..., b - 1}.
648
    template <typename Number>
649
    Number operator[](Number b) {
650
      return _random_bits::Mapping<Number, Word>::map(core, b);
651
    }
652

	
653
    /// \brief Returns a random non-negative integer
654
    ///
655
    /// It returns a random non-negative integer uniformly from the
656
    /// whole range of the current \c Number type.  The default result
657
    /// type of this function is unsigned int.
658
    template <typename Number>
659
    Number uinteger() {
660
      return _random_bits::IntConversion<Number, Word>::convert(core);
661
    }
662

	
663
    unsigned int uinteger() {
664
      return uinteger<unsigned int>();
665
    }
666

	
667
    /// \brief Returns a random integer
668
    ///
669
    /// It returns a random integer uniformly from the whole range of
670
    /// the current \c Number type. The default result type of this
671
    /// function is int.
672
    template <typename Number>
673
    Number integer() {
674
      static const int nb = std::numeric_limits<Number>::digits + 
675
        (std::numeric_limits<Number>::is_signed ? 1 : 0);
676
      return _random_bits::IntConversion<Number, Word, nb>::convert(core);
677
    }
678

	
679
    int integer() {
680
      return integer<int>();
681
    }
682
    
683
    /// \brief Returns a random bool
684
    ///
685
    /// It returns a random bool. The generator holds a buffer for
686
    /// random bits. Every time when it become empty the generator makes
687
    /// a new random word and fill the buffer up.
688
    bool boolean() {
689
      return bool_producer.convert(core);
690
    }
691

	
692
    ///\name Nonuniform distributions
693
    ///
694
    
695
    ///@{
696
    
697
    /// \brief Returns a random bool
698
    ///
699
    /// It returns a random bool with given probability of true result
700
    bool boolean(double p) {
701
      return operator()() < p;
702
    }
703

	
704
    /// Standard Gauss distribution
705

	
706
    /// Standard Gauss distribution.
707
    /// \note The Cartesian form of the Box-Muller
708
    /// transformation is used to generate a random normal distribution.
709
    /// \todo Consider using the "ziggurat" method instead.
710
    double gauss() 
711
    {
712
      double V1,V2,S;
713
      do {
714
	V1=2*real<double>()-1;
715
	V2=2*real<double>()-1;
716
	S=V1*V1+V2*V2;
717
      } while(S>=1);
718
      return std::sqrt(-2*std::log(S)/S)*V1;
719
    }
720
    /// Gauss distribution with given mean and standard deviation
721

	
722
    /// Gauss distribution with given mean and standard deviation
723
    /// \sa gauss()
724
    double gauss(double mean,double std_dev)
725
    {
726
      return gauss()*std_dev+mean;
727
    }
728

	
729
    /// Exponential distribution with given mean
730

	
731
    /// This function generates an exponential distribution random number
732
    /// with mean <tt>1/lambda</tt>.
733
    ///
734
    double exponential(double lambda=1.0)
735
    {
736
      return -std::log(1.0-real<double>())/lambda;
737
    }
738

	
739
    /// Gamma distribution with given integer shape
740

	
741
    /// This function generates a gamma distribution random number.
742
    /// 
743
    ///\param k shape parameter (<tt>k>0</tt> integer)
744
    double gamma(int k) 
745
    {
746
      double s = 0;
747
      for(int i=0;i<k;i++) s-=std::log(1.0-real<double>());
748
      return s;
749
    }
750
    
751
    /// Gamma distribution with given shape and scale parameter
752

	
753
    /// This function generates a gamma distribution random number.
754
    /// 
755
    ///\param k shape parameter (<tt>k>0</tt>)
756
    ///\param theta scale parameter
757
    ///
758
    double gamma(double k,double theta=1.0)
759
    {
760
      double xi,nu;
761
      const double delta = k-std::floor(k);
762
      const double v0=M_E/(M_E-delta);
763
      do {
764
	double V0=1.0-real<double>();
765
	double V1=1.0-real<double>();
766
	double V2=1.0-real<double>();
767
	if(V2<=v0) 
768
	  {
769
	    xi=std::pow(V1,1.0/delta);
770
	    nu=V0*std::pow(xi,delta-1.0);
771
	  }
772
	else 
773
	  {
774
	    xi=1.0-std::log(V1);
775
	    nu=V0*std::exp(-xi);
776
	  }
777
      } while(nu>std::pow(xi,delta-1.0)*std::exp(-xi));
778
      return theta*(xi-gamma(int(std::floor(k))));
779
    }
780
    
781
    /// Weibull distribution
782

	
783
    /// This function generates a Weibull distribution random number.
784
    /// 
785
    ///\param k shape parameter (<tt>k>0</tt>)
786
    ///\param lambda scale parameter (<tt>lambda>0</tt>)
787
    ///
788
    double weibull(double k,double lambda)
789
    {
790
      return lambda*pow(-std::log(1.0-real<double>()),1.0/k);
791
    }  
792
      
793
    /// Pareto distribution
794

	
795
    /// This function generates a Pareto distribution random number.
796
    /// 
797
    ///\param k shape parameter (<tt>k>0</tt>)
798
    ///\param x_min location parameter (<tt>x_min>0</tt>)
799
    ///
800
    double pareto(double k,double x_min)
801
    {
802
      return exponential(gamma(k,1.0/x_min));
803
    }  
804
      
805
    ///@}
806
    
807
    ///\name Two dimensional distributions
808
    ///
809

	
810
    ///@{
811
    
812
    /// Uniform distribution on the full unit circle.
813

	
814
    /// Uniform distribution on the full unit circle.
815
    ///
816
    dim2::Point<double> disc() 
817
    {
818
      double V1,V2;
819
      do {
820
	V1=2*real<double>()-1;
821
	V2=2*real<double>()-1;
822
	
823
      } while(V1*V1+V2*V2>=1);
824
      return dim2::Point<double>(V1,V2);
825
    }
826
    /// A kind of two dimensional Gauss distribution
827

	
828
    /// This function provides a turning symmetric two-dimensional distribution.
829
    /// Both coordinates are of standard normal distribution, but they are not
830
    /// independent.
831
    ///
832
    /// \note The coordinates are the two random variables provided by
833
    /// the Box-Muller method.
834
    dim2::Point<double> gauss2()
835
    {
836
      double V1,V2,S;
837
      do {
838
	V1=2*real<double>()-1;
839
	V2=2*real<double>()-1;
840
	S=V1*V1+V2*V2;
841
      } while(S>=1);
842
      double W=std::sqrt(-2*std::log(S)/S);
843
      return dim2::Point<double>(W*V1,W*V2);
844
    }
845
    /// A kind of two dimensional exponential distribution
846

	
847
    /// This function provides a turning symmetric two-dimensional distribution.
848
    /// The x-coordinate is of conditionally exponential distribution
849
    /// with the condition that x is positive and y=0. If x is negative and 
850
    /// y=0 then, -x is of exponential distribution. The same is true for the
851
    /// y-coordinate.
852
    dim2::Point<double> exponential2() 
853
    {
854
      double V1,V2,S;
855
      do {
856
	V1=2*real<double>()-1;
857
	V2=2*real<double>()-1;
858
	S=V1*V1+V2*V2;
859
      } while(S>=1);
860
      double W=-std::log(S)/S;
861
      return dim2::Point<double>(W*V1,W*V2);
862
    }
863

	
864
    ///@}    
865
  };
866

	
867

	
868
  extern Random rnd;
869

	
870
}
871

	
872
#endif
Ignore white space 6 line context
1
/* -*- C++ -*-
2
 *
3
 * This file is a part of LEMON, a generic C++ optimization library
4
 *
5
 * Copyright (C) 2003-2007
6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8
 *
9
 * Permission to use, modify and distribute this software is granted
10
 * provided that this copyright notice appears in all copies. For
11
 * precise terms see the accompanying LICENSE file.
12
 *
13
 * This software is provided "AS IS" with no warranty of any kind,
14
 * express or implied, and with no claim as to its suitability for any
15
 * purpose.
16
 *
17
 */
18

	
19
#include <lemon/random.h>
20
#include "test_tools.h"
21

	
22
///\file \brief Test cases for random.h
23
///
24
///\todo To be extended
25
///
26

	
27
int main()
28
{
29
  double a=lemon::rnd();
30
  check(a<1.0&&a>0.0,"This should be in [0,1)");
31
  a=lemon::rnd.gauss();
32
  a=lemon::rnd.gamma(3.45,0);
33
  a=lemon::rnd.gamma(4);
34
  //Does gamma work with integer k?
35
  a=lemon::rnd.gamma(4.0,0);
36
}
Ignore white space 48 line context
1 1
syntax: glob
2 2
*.obj
3 3
*.orig
4 4
*.rej
5 5
*~
6 6
*.o
7 7
.#.*
8
*.log
9
*.lo
10
*.tar.*
8 11
Makefile.in
9 12
aclocal.m4
10 13
config.h.in
11 14
configure
12 15
Makefile
13 16
config.h
14 17
config.log
15 18
config.status
16 19
libtool
17 20
stamp-h1
18 21
lemon/lemon.pc
19 22
lemon/libemon.la
20 23
lemon/stamp-h2
21 24
doc/Doxyfile
22
lemon/.dirstamp
23
lemon/.libs/*
25
.dirstamp
26
.libs/*
27
.deps/*
24 28

	
25 29
syntax: regexp
26
html/.*
27
autom4te.cache/.*
28
build-aux/.*
29
objs.*/.*
30
^doc/html/.*
31
^autom4te.cache/.*
32
^build-aux/.*
33
^objs.*/.*
34
^test/[a-z_]*$
... ...
 No newline at end of file
Ignore white space 6 line context
1 1
EXTRA_DIST += \
2 2
	lemon/Makefile \
3 3
	lemon/lemon.pc.in
4 4

	
5 5
pkgconfig_DATA += lemon/lemon.pc
6 6

	
7 7
lib_LTLIBRARIES += lemon/libemon.la
8 8

	
9 9
lemon_libemon_la_SOURCES = \
10
        lemon/base.cc
10
        lemon/base.cc \
11
        lemon/random.cc
12

	
11 13

	
12 14
lemon_libemon_la_CXXFLAGS = $(GLPK_CFLAGS) $(CPLEX_CFLAGS) $(SOPLEX_CXXFLAGS)
13 15
lemon_libemon_la_LDFLAGS = $(GLPK_LIBS) $(CPLEX_LIBS) $(SOPLEX_LIBS)
14 16

	
15 17
lemon_HEADERS += \
16 18
        lemon/dim2.h \
19
        lemon/random.h \
17 20
	lemon/list_graph.h \
18 21
        lemon/tolerance.h
19 22

	
20 23
bits_HEADERS += \
21 24
        lemon/bits/invalid.h \
22 25
        lemon/bits/utility.h
23 26

	
24 27
concept_HEADERS +=
Ignore white space 6 line context
... ...
@@ -3,52 +3,52 @@
3 3
 * This file is a part of LEMON, a generic C++ optimization library
4 4
 *
5 5
 * Copyright (C) 2003-2007
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_BITS_INVALID_H
20 20
#define LEMON_BITS_INVALID_H
21 21

	
22 22
///\file
23 23
///\brief Definition of INVALID.
24 24

	
25 25
namespace lemon {
26 26

	
27
  /// \brief Dummy type to make it easier to make invalid iterators.
27
  /// \brief Dummy type to make it easier to create invalid iterators.
28 28
  ///
29 29
  /// See \ref INVALID for the usage.
30 30
  struct Invalid {
31 31
  public:
32 32
    bool operator==(Invalid) { return true;  }
33 33
    bool operator!=(Invalid) { return false; }
34 34
    bool operator< (Invalid) { return false; }
35 35
  };
36 36
  
37
  /// Invalid iterators.
38
  
37
  /// \brief Invalid iterators.
38
  ///
39 39
  /// \ref Invalid is a global type that converts to each iterator
40 40
  /// in such a way that the value of the target iterator will be invalid.
41 41

	
42 42
  //Some people didn't like this:
43 43
  //const Invalid &INVALID = *(Invalid *)0;
44 44

	
45 45
#ifdef LEMON_ONLY_TEMPLATES
46 46
  const Invalid INVALID = Invalid();
47 47
#else
48 48
  extern const Invalid INVALID;
49 49
#endif
50 50

	
51 51
} //namespace lemon
52 52

	
53 53
#endif
54 54
  
Ignore white space 6 line context
... ...
@@ -13,91 +13,88 @@
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_DIM2_H
20 20
#define LEMON_DIM2_H
21 21

	
22 22
#include <iostream>
23 23
#include <lemon/bits/utility.h>
24 24

	
25 25
///\ingroup misc
26 26
///\file
27 27
///\brief A simple two dimensional vector and a bounding box implementation 
28 28
///
29 29
/// The class \ref lemon::dim2::Point "dim2::Point" implements
30 30
///a two dimensional vector with the usual
31 31
/// operations.
32 32
///
33 33
/// The class \ref lemon::dim2::BoundingBox "dim2::BoundingBox"
34 34
/// can be used to determine
35 35
/// the rectangular bounding box of a set of
36 36
/// \ref lemon::dim2::Point "dim2::Point"'s.
37
///
38
///\author Attila Bernath
39

	
40 37

	
41 38
namespace lemon {
42 39

	
43 40
  ///Tools for handling two dimensional coordinates
44 41

	
45 42
  ///This namespace is a storage of several
46 43
  ///tools for handling two dimensional coordinates
47 44
  namespace dim2 {
48 45

	
49 46
  /// \addtogroup misc
50 47
  /// @{
51 48

	
52 49
  /// A simple two dimensional vector (plainvector) implementation
53 50

	
54 51
  /// A simple two dimensional vector (plainvector) implementation
55 52
  ///with the usual vector
56 53
  /// operators.
57 54
  ///
58 55
  template<typename T>
59 56
    class Point {
60 57

	
61 58
    public:
62 59

	
63 60
      typedef T Value;
64 61

	
65
      ///First co-ordinate
62
      ///First coordinate
66 63
      T x;
67
      ///Second co-ordinate
64
      ///Second coordinate
68 65
      T y;     
69 66
      
70 67
      ///Default constructor
71 68
      Point() {}
72 69

	
73 70
      ///Construct an instance from coordinates
74 71
      Point(T a, T b) : x(a), y(b) { }
75 72

	
76 73
      ///The dimension of the vector.
77 74

	
78
      ///This class give back always 2.
79
      ///
75
      ///The dimension of the vector.
76
      ///This function always returns 2. 
80 77
      int size() const { return 2; }
81 78

	
82 79
      ///Subscripting operator
83 80

	
84 81
      ///\c p[0] is \c p.x and \c p[1] is \c p.y
85 82
      ///
86 83
      T& operator[](int idx) { return idx == 0 ? x : y; }
87 84

	
88 85
      ///Const subscripting operator
89 86

	
90 87
      ///\c p[0] is \c p.x and \c p[1] is \c p.y
91 88
      ///
92 89
      const T& operator[](int idx) const { return idx == 0 ? x : y; }
93 90

	
94 91
      ///Conversion constructor
95 92
      template<class TT> Point(const Point<TT> &p) : x(p.x), y(p.y) {}
96 93

	
97 94
      ///Give back the square of the norm of the vector
98 95
      T normSquare() const {
99 96
        return x*x+y*y;
100 97
      }
101 98
  
102 99
      ///Increment the left hand side by u
103 100
      Point<T>& operator +=(const Point<T>& u) {
... ...
@@ -117,427 +114,450 @@
117 114
      Point<T>& operator *=(const T &u) {
118 115
        x *= u;
119 116
        y *= u;
120 117
        return *this;
121 118
      }
122 119

	
123 120
      ///Divide the left hand side by a scalar
124 121
      Point<T>& operator /=(const T &u) {
125 122
        x /= u;
126 123
        y /= u;
127 124
        return *this;
128 125
      }
129 126
  
130 127
      ///Return the scalar product of two vectors
131 128
      T operator *(const Point<T>& u) const {
132 129
        return x*u.x+y*u.y;
133 130
      }
134 131
  
135 132
      ///Return the sum of two vectors
136 133
      Point<T> operator+(const Point<T> &u) const {
137 134
        Point<T> b=*this;
138 135
        return b+=u;
139 136
      }
140 137

	
141
      ///Return the neg of the vectors
138
      ///Return the negative of the vector
142 139
      Point<T> operator-() const {
143 140
        Point<T> b=*this;
144 141
        b.x=-b.x; b.y=-b.y;
145 142
        return b;
146 143
      }
147 144

	
148 145
      ///Return the difference of two vectors
149 146
      Point<T> operator-(const Point<T> &u) const {
150 147
        Point<T> b=*this;
151 148
        return b-=u;
152 149
      }
153 150

	
154 151
      ///Return a vector multiplied by a scalar
155 152
      Point<T> operator*(const T &u) const {
156 153
        Point<T> b=*this;
157 154
        return b*=u;
158 155
      }
159 156

	
160 157
      ///Return a vector divided by a scalar
161 158
      Point<T> operator/(const T &u) const {
162 159
        Point<T> b=*this;
163 160
        return b/=u;
164 161
      }
165 162

	
166 163
      ///Test equality
167 164
      bool operator==(const Point<T> &u) const {
168 165
        return (x==u.x) && (y==u.y);
169 166
      }
170 167

	
171 168
      ///Test inequality
172 169
      bool operator!=(Point u) const {
173 170
        return  (x!=u.x) || (y!=u.y);
174 171
      }
175 172

	
176 173
    };
177 174

	
178
  ///Return an Point 
175
  ///Return a Point 
179 176

	
180
  ///Return an Point
177
  ///Return a Point.
181 178
  ///\relates Point
182 179
  template <typename T>
183 180
  inline Point<T> makePoint(const T& x, const T& y) {
184 181
    return Point<T>(x, y);
185 182
  }
186 183

	
187 184
  ///Return a vector multiplied by a scalar
188 185

	
189
  ///Return a vector multiplied by a scalar
186
  ///Return a vector multiplied by a scalar.
190 187
  ///\relates Point
191 188
  template<typename T> Point<T> operator*(const T &u,const Point<T> &x) {
192 189
    return x*u;
193 190
  }
194 191

	
195 192
  ///Read a plainvector from a stream
196 193

	
197
  ///Read a plainvector from a stream
194
  ///Read a plainvector from a stream.
198 195
  ///\relates Point
199 196
  ///
200 197
  template<typename T>
201 198
  inline std::istream& operator>>(std::istream &is, Point<T> &z) {
202 199
    char c;
203 200
    if (is >> c) {
204 201
      if (c != '(') is.putback(c);
205 202
    } else {
206 203
      is.clear();
207 204
    }
208 205
    if (!(is >> z.x)) return is;
209 206
    if (is >> c) {
210 207
      if (c != ',') is.putback(c);
211 208
    } else {
212 209
      is.clear();
213 210
    }
214 211
    if (!(is >> z.y)) return is;
215 212
    if (is >> c) {
216 213
      if (c != ')') is.putback(c);
217 214
    } else {
218 215
      is.clear();
219 216
    }
220 217
    return is;
221 218
  }
222 219

	
223 220
  ///Write a plainvector to a stream
224 221

	
225
  ///Write a plainvector to a stream
222
  ///Write a plainvector to a stream.
226 223
  ///\relates Point
227 224
  ///
228 225
  template<typename T>
229 226
  inline std::ostream& operator<<(std::ostream &os, const Point<T>& z)
230 227
  {
231 228
    os << "(" << z.x << ", " << z.y << ")";
232 229
    return os;
233 230
  }
234 231

	
235 232
  ///Rotate by 90 degrees
236 233

	
237
  ///Returns its parameter rotated by 90 degrees in positive direction.
234
  ///Returns the parameter rotated by 90 degrees in positive direction.
238 235
  ///\relates Point
239 236
  ///
240 237
  template<typename T>
241 238
  inline Point<T> rot90(const Point<T> &z)
242 239
  {
243 240
    return Point<T>(-z.y,z.x);
244 241
  }
245 242

	
246 243
  ///Rotate by 180 degrees
247 244

	
248
  ///Returns its parameter rotated by 180 degrees.
245
  ///Returns the parameter rotated by 180 degrees.
249 246
  ///\relates Point
250 247
  ///
251 248
  template<typename T>
252 249
  inline Point<T> rot180(const Point<T> &z)
253 250
  {
254 251
    return Point<T>(-z.x,-z.y);
255 252
  }
256 253

	
257 254
  ///Rotate by 270 degrees
258 255

	
259
  ///Returns its parameter rotated by 90 degrees in negative direction.
256
  ///Returns the parameter rotated by 90 degrees in negative direction.
260 257
  ///\relates Point
261 258
  ///
262 259
  template<typename T>
263 260
  inline Point<T> rot270(const Point<T> &z)
264 261
  {
265 262
    return Point<T>(z.y,-z.x);
266 263
  }
267 264

	
268 265
  
269 266

	
270 267
  /// A class to calculate or store the bounding box of plainvectors.
271 268

	
272 269
  /// A class to calculate or store the bounding box of plainvectors.
273 270
  ///
274
  ///\author Attila Bernath
275 271
    template<typename T>
276 272
    class BoundingBox {
277 273
      Point<T> bottom_left, top_right;
278 274
      bool _empty;
279 275
    public:
280 276
      
281 277
      ///Default constructor: creates an empty bounding box
282 278
      BoundingBox() { _empty = true; }
283 279

	
284 280
      ///Construct an instance from one point
285 281
      BoundingBox(Point<T> a) { bottom_left=top_right=a; _empty = false; }
286 282
      
287 283
      ///Construct an instance from two points
288 284
      
289
      ///Construct an instance from two points
290
      ///\warning The coordinates of the bottom-left corner must be no more
291
      ///than those of the top-right one
285
      ///Construct an instance from two points.
286
      ///\param a The bottom left corner.
287
      ///\param b The top right corner.
288
      ///\warning The coordinates of the bottom left corner must be no more
289
      ///than those of the top right one.
292 290
      BoundingBox(Point<T> a,Point<T> b)
293 291
      {
294 292
	bottom_left=a;
295 293
	top_right=b;
296 294
	_empty = false;
297 295
      }
298 296
      
299 297
      ///Construct an instance from four numbers
300 298

	
301
      ///Construct an instance from four numbers
302
      ///\warning The coordinates of the bottom-left corner must be no more
303
      ///than those of the top-right one
299
      ///Construct an instance from four numbers.
300
      ///\param l The left side of the box.
301
      ///\param b The bottom of the box.
302
      ///\param r The right side of the box.
303
      ///\param t The top of the box.
304
      ///\warning The left side must be no more than the right side and
305
      ///bottom must be no more than the top. 
304 306
      BoundingBox(T l,T b,T r,T t)
305 307
      {
306 308
	bottom_left=Point<T>(l,b);
307 309
	top_right=Point<T>(r,t);
308 310
	_empty = false;
309 311
      }
310 312
      
311
      ///Were any points added?
313
      ///Return \c true if the bounding box is empty.
314
      
315
      ///Return \c true if the bounding box is empty (i.e. return \c false
316
      ///if at least one point was added to the box or the coordinates of
317
      ///the box were set).
318
      ///The coordinates of an empty bounding box are not defined. 
312 319
      bool empty() const {
313 320
        return _empty;
314 321
      }
315 322
      
316 323
      ///Make the BoundingBox empty
317 324
      void clear() {
318 325
        _empty=1;
319 326
      }
320 327

	
321 328
      ///Give back the bottom left corner
322 329

	
323 330
      ///Give back the bottom left corner.
324 331
      ///If the bounding box is empty, then the return value is not defined.
325 332
      Point<T> bottomLeft() const {
326 333
        return bottom_left;
327 334
      }
328 335

	
329 336
      ///Set the bottom left corner
330 337

	
331 338
      ///Set the bottom left corner.
332
      ///It should only bee used for non-empty box.
339
      ///It should only be used for non-empty box.
333 340
      void bottomLeft(Point<T> p) {
334 341
	bottom_left = p;
335 342
      }
336 343

	
337 344
      ///Give back the top right corner
338 345

	
339 346
      ///Give back the top right corner.
340 347
      ///If the bounding box is empty, then the return value is not defined.
341 348
      Point<T> topRight() const {
342 349
        return top_right;
343 350
      }
344 351

	
345 352
      ///Set the top right corner
346 353

	
347 354
      ///Set the top right corner.
348
      ///It should only bee used for non-empty box.
355
      ///It should only be used for non-empty box.
349 356
      void topRight(Point<T> p) {
350 357
	top_right = p;
351 358
      }
352 359

	
353 360
      ///Give back the bottom right corner
354 361

	
355 362
      ///Give back the bottom right corner.
356 363
      ///If the bounding box is empty, then the return value is not defined.
357 364
      Point<T> bottomRight() const {
358 365
        return Point<T>(top_right.x,bottom_left.y);
359 366
      }
360 367

	
361 368
      ///Set the bottom right corner
362 369

	
363 370
      ///Set the bottom right corner.
364
      ///It should only bee used for non-empty box.
371
      ///It should only be used for non-empty box.
365 372
      void bottomRight(Point<T> p) {
366 373
	top_right.x = p.x;
367 374
	bottom_left.y = p.y;
368 375
      }
369 376
 
370 377
      ///Give back the top left corner
371 378

	
372 379
      ///Give back the top left corner.
373 380
      ///If the bounding box is empty, then the return value is not defined.
374 381
      Point<T> topLeft() const {
375 382
        return Point<T>(bottom_left.x,top_right.y);
376 383
      }
377 384

	
378 385
      ///Set the top left corner
379 386

	
380 387
      ///Set the top left corner.
381
      ///It should only bee used for non-empty box.
388
      ///It should only be used for non-empty box.
382 389
      void topLeft(Point<T> p) {
383 390
	top_right.y = p.y;
384 391
	bottom_left.x = p.x;
385 392
      }
386 393

	
387 394
      ///Give back the bottom of the box
388 395

	
389 396
      ///Give back the bottom of the box.
390 397
      ///If the bounding box is empty, then the return value is not defined.
391 398
      T bottom() const {
392 399
        return bottom_left.y;
393 400
      }
394 401

	
395 402
      ///Set the bottom of the box
396 403

	
397 404
      ///Set the bottom of the box.
398
      ///It should only bee used for non-empty box.
405
      ///It should only be used for non-empty box.
399 406
      void bottom(T t) {
400 407
	bottom_left.y = t;
401 408
      }
402 409

	
403 410
      ///Give back the top of the box
404 411

	
405 412
      ///Give back the top of the box.
406 413
      ///If the bounding box is empty, then the return value is not defined.
407 414
      T top() const {
408 415
        return top_right.y;
409 416
      }
410 417

	
411 418
      ///Set the top of the box
412 419

	
413 420
      ///Set the top of the box.
414
      ///It should only bee used for non-empty box.
421
      ///It should only be used for non-empty box.
415 422
      void top(T t) {
416 423
	top_right.y = t;
417 424
      }
418 425

	
419 426
      ///Give back the left side of the box
420 427

	
421 428
      ///Give back the left side of the box.
422 429
      ///If the bounding box is empty, then the return value is not defined.
423 430
      T left() const {
424 431
        return bottom_left.x;
425 432
      }
426 433
 
427 434
      ///Set the left side of the box
428 435

	
429 436
      ///Set the left side of the box.
430
      ///It should only bee used for non-empty box
437
      ///It should only be used for non-empty box.
431 438
      void left(T t) {
432 439
	bottom_left.x = t;
433 440
      }
434 441

	
435 442
      /// Give back the right side of the box
436 443

	
437 444
      /// Give back the right side of the box.
438 445
      ///If the bounding box is empty, then the return value is not defined.
439 446
      T right() const {
440 447
        return top_right.x;
441 448
      }
442 449

	
443 450
      ///Set the right side of the box
444 451

	
445 452
      ///Set the right side of the box.
446
      ///It should only bee used for non-empty box
453
      ///It should only be used for non-empty box.
447 454
      void right(T t) {
448 455
	top_right.x = t;
449 456
      }
450 457

	
451 458
      ///Give back the height of the box
452 459

	
453 460
      ///Give back the height of the box.
454 461
      ///If the bounding box is empty, then the return value is not defined.
455 462
      T height() const {
456 463
        return top_right.y-bottom_left.y;
457 464
      }
458 465

	
459 466
      ///Give back the width of the box
460 467

	
461 468
      ///Give back the width of the box.
462 469
      ///If the bounding box is empty, then the return value is not defined.
463 470
      T width() const {
464 471
        return top_right.x-bottom_left.x;
465 472
      }
466 473

	
467 474
      ///Checks whether a point is inside a bounding box
468
      bool inside(const Point<T>& u){
475
      bool inside(const Point<T>& u) const {
469 476
        if (_empty)
470 477
          return false;
471 478
        else{
472 479
          return ((u.x-bottom_left.x)*(top_right.x-u.x) >= 0 &&
473 480
              (u.y-bottom_left.y)*(top_right.y-u.y) >= 0 );
474 481
        }
475 482
      }
476 483
  
477 484
      ///Increments a bounding box with a point
485

	
486
      ///Increments a bounding box with a point.
487
      ///
478 488
      BoundingBox& add(const Point<T>& u){
479 489
        if (_empty){
480 490
          bottom_left=top_right=u;
481 491
          _empty = false;
482 492
        }
483 493
        else{
484 494
          if (bottom_left.x > u.x) bottom_left.x = u.x;
485 495
          if (bottom_left.y > u.y) bottom_left.y = u.y;
486 496
          if (top_right.x < u.x) top_right.x = u.x;
487 497
          if (top_right.y < u.y) top_right.y = u.y;
488 498
        }
489 499
        return *this;
490 500
      }
491 501
    
492
      ///Increments a bounding to contain another bounding box
502
      ///Increments a bounding box to contain another bounding box
503
      
504
      ///Increments a bounding box to contain another bounding box.
505
      ///
493 506
      BoundingBox& add(const BoundingBox &u){
494 507
        if ( !u.empty() ){
495 508
          this->add(u.bottomLeft());
496 509
	  this->add(u.topRight());
497 510
        }
498 511
        return *this;
499 512
      }
500 513
  
501 514
      ///Intersection of two bounding boxes
502
      BoundingBox operator &(const BoundingBox& u){
515

	
516
      ///Intersection of two bounding boxes.
517
      ///
518
      BoundingBox operator&(const BoundingBox& u) const {
503 519
        BoundingBox b;
504
	b.bottom_left.x=std::max(this->bottom_left.x,u.bottom_left.x);
505
	b.bottom_left.y=std::max(this->bottom_left.y,u.bottom_left.y);
506
	b.top_right.x=std::min(this->top_right.x,u.top_right.x);
507
	b.top_right.y=std::min(this->top_right.y,u.top_right.y);
508
	b._empty = this->_empty || u._empty ||
509
	  b.bottom_left.x>top_right.x && b.bottom_left.y>top_right.y;
520
        if (this->_empty || u._empty) {
521
	  b._empty = true;
522
	} else {
523
	  b.bottom_left.x = std::max(this->bottom_left.x,u.bottom_left.x);
524
	  b.bottom_left.y = std::max(this->bottom_left.y,u.bottom_left.y);
525
	  b.top_right.x = std::min(this->top_right.x,u.top_right.x);
526
	  b.top_right.y = std::min(this->top_right.y,u.top_right.y);
527
	  b._empty = b.bottom_left.x > b.top_right.x ||
528
	             b.bottom_left.y > b.top_right.y;
529
	} 
510 530
        return b;
511 531
      }
512 532

	
513 533
    };//class Boundingbox
514 534

	
515 535

	
516
  ///Map of x-coordinates of a dim2::Point<>-map
536
  ///Map of x-coordinates of a \ref Point "Point"-map
517 537

	
518 538
  ///\ingroup maps
519
  ///Map of x-coordinates of a dim2::Point<>-map
539
  ///Map of x-coordinates of a \ref Point "Point"-map.
520 540
  ///
521 541
  template<class M>
522 542
  class XMap 
523 543
  {
524 544
    M& _map;
525 545
  public:
526 546

	
527 547
    typedef typename M::Value::Value Value;
528 548
    typedef typename M::Key Key;
529 549
    ///\e
530 550
    XMap(M& map) : _map(map) {}
531 551
    Value operator[](Key k) const {return _map[k].x;}
532 552
    void set(Key k,Value v) {_map.set(k,typename M::Value(v,_map[k].y));}
533 553
  };
534 554
    
535 555
  ///Returns an \ref XMap class
536 556

	
537 557
  ///This function just returns an \ref XMap class.
538 558
  ///
539 559
  ///\ingroup maps
540 560
  ///\relates XMap
541 561
  template<class M> 
542 562
  inline XMap<M> xMap(M &m) 
543 563
  {
... ...
@@ -549,141 +569,141 @@
549 569
  {
550 570
    return XMap<M>(m);
551 571
  }
552 572

	
553 573
  ///Constant (read only) version of \ref XMap
554 574

	
555 575
  ///\ingroup maps
556 576
  ///Constant (read only) version of \ref XMap
557 577
  ///
558 578
  template<class M>
559 579
  class ConstXMap 
560 580
  {
561 581
    const M& _map;
562 582
  public:
563 583

	
564 584
    typedef typename M::Value::Value Value;
565 585
    typedef typename M::Key Key;
566 586
    ///\e
567 587
    ConstXMap(const M &map) : _map(map) {}
568 588
    Value operator[](Key k) const {return _map[k].x;}
569 589
  };
570 590
    
571 591
  ///Returns a \ref ConstXMap class
572 592

	
573
  ///This function just returns an \ref ConstXMap class.
593
  ///This function just returns a \ref ConstXMap class.
574 594
  ///
575 595
  ///\ingroup maps
576 596
  ///\relates ConstXMap
577 597
  template<class M> 
578 598
  inline ConstXMap<M> xMap(const M &m) 
579 599
  {
580 600
    return ConstXMap<M>(m);
581 601
  }
582 602

	
583
  ///Map of y-coordinates of a dim2::Point<>-map
603
  ///Map of y-coordinates of a \ref Point "Point"-map
584 604
    
585 605
  ///\ingroup maps
586
  ///Map of y-coordinates of a dim2::Point<>-map
606
  ///Map of y-coordinates of a \ref Point "Point"-map.
587 607
  ///
588 608
  template<class M>
589 609
  class YMap 
590 610
  {
591 611
    M& _map;
592 612
  public:
593 613

	
594 614
    typedef typename M::Value::Value Value;
595 615
    typedef typename M::Key Key;
596 616
    ///\e
597 617
    YMap(M& map) : _map(map) {}
598 618
    Value operator[](Key k) const {return _map[k].y;}
599 619
    void set(Key k,Value v) {_map.set(k,typename M::Value(_map[k].x,v));}
600 620
  };
601 621

	
602
  ///Returns an \ref YMap class
622
  ///Returns a \ref YMap class
603 623

	
604
  ///This function just returns an \ref YMap class.
624
  ///This function just returns a \ref YMap class.
605 625
  ///
606 626
  ///\ingroup maps
607 627
  ///\relates YMap
608 628
  template<class M> 
609 629
  inline YMap<M> yMap(M &m) 
610 630
  {
611 631
    return YMap<M>(m);
612 632
  }
613 633

	
614 634
  template<class M> 
615 635
  inline YMap<M> yMap(const M &m) 
616 636
  {
617 637
    return YMap<M>(m);
618 638
  }
619 639

	
620 640
  ///Constant (read only) version of \ref YMap
621 641

	
622 642
  ///\ingroup maps
623 643
  ///Constant (read only) version of \ref YMap
624 644
  ///
625 645
  template<class M>
626 646
  class ConstYMap 
627 647
  {
628 648
    const M& _map;
629 649
  public:
630 650

	
631 651
    typedef typename M::Value::Value Value;
632 652
    typedef typename M::Key Key;
633 653
    ///\e
634 654
    ConstYMap(const M &map) : _map(map) {}
635 655
    Value operator[](Key k) const {return _map[k].y;}
636 656
  };
637 657
    
638 658
  ///Returns a \ref ConstYMap class
639 659

	
640
  ///This function just returns an \ref ConstYMap class.
660
  ///This function just returns a \ref ConstYMap class.
641 661
  ///
642 662
  ///\ingroup maps
643 663
  ///\relates ConstYMap
644 664
  template<class M> 
645 665
  inline ConstYMap<M> yMap(const M &m) 
646 666
  {
647 667
    return ConstYMap<M>(m);
648 668
  }
649 669

	
650 670

	
651 671
    ///\brief Map of the \ref Point::normSquare() "normSquare()"
652
    ///of an \ref Point "Point"-map
672
    ///of a \ref Point "Point"-map
653 673
    ///
654 674
    ///Map of the \ref Point::normSquare() "normSquare()"
655
    ///of an \ref Point "Point"-map
675
    ///of a \ref Point "Point"-map.
656 676
    ///\ingroup maps
657 677
    ///
658 678
  template<class M>
659 679
  class NormSquareMap 
660 680
  {
661 681
    const M& _map;
662 682
  public:
663 683

	
664 684
    typedef typename M::Value::Value Value;
665 685
    typedef typename M::Key Key;
666 686
    ///\e
667 687
    NormSquareMap(const M &map) : _map(map) {}
668 688
    Value operator[](Key k) const {return _map[k].normSquare();}
669 689
  };
670 690
    
671 691
  ///Returns a \ref NormSquareMap class
672 692

	
673
  ///This function just returns an \ref NormSquareMap class.
693
  ///This function just returns a \ref NormSquareMap class.
674 694
  ///
675 695
  ///\ingroup maps
676 696
  ///\relates NormSquareMap
677 697
  template<class M> 
678 698
  inline NormSquareMap<M> normSquareMap(const M &m) 
679 699
  {
680 700
    return NormSquareMap<M>(m);
681 701
  }
682 702

	
683 703
  /// @}
684 704

	
685 705
  } //namespce dim2
686 706
  
687 707
} //namespace lemon
688 708

	
689 709
#endif //LEMON_DIM2_H
Ignore white space 6 line context
... ...
@@ -27,51 +27,55 @@
27 27
///\todo It should be in a module like "Basic tools"
28 28

	
29 29

	
30 30
namespace lemon {
31 31

	
32 32
  /// \addtogroup misc
33 33
  /// @{
34 34
  
35 35
  ///\brief A class to provide a basic way to
36 36
  ///handle the comparison of numbers that are obtained
37 37
  ///as a result of a probably inexact computation.
38 38
  ///
39 39
  ///Tolerance is a class to provide a basic way to
40 40
  ///handle the comparison of numbers that are obtained
41 41
  ///as a result of a probably inexact computation.
42 42
  ///
43 43
  ///This is an abstract class, it should be specialized for all numerical
44 44
  ///data types. These specialized classes like \ref Tolerance\<double\>
45 45
  ///may offer additional tuning parameters.
46 46
  ///
47 47
  ///\sa Tolerance<float>
48 48
  ///\sa Tolerance<double>
49 49
  ///\sa Tolerance<long double>
50 50
  ///\sa Tolerance<int>
51
#if defined __GNUC__ && !defined __STRICT_ANSI__  
51 52
  ///\sa Tolerance<long long int>
53
#endif
52 54
  ///\sa Tolerance<unsigned int>
55
#if defined __GNUC__ && !defined __STRICT_ANSI__  
53 56
  ///\sa Tolerance<unsigned long long int>
57
#endif
54 58

	
55 59
  template<class T>
56 60
  class Tolerance
57 61
  {
58 62
  public:
59 63
    typedef T Value;
60 64

	
61 65
    ///\name Comparisons
62 66
    ///The concept is that these bool functions return with \c true only if
63 67
    ///the related comparisons hold even if some numerical error appeared
64 68
    ///during the computations.
65 69

	
66 70
    ///@{
67 71

	
68 72
    ///Returns \c true if \c a is \e surely strictly less than \c b
69 73
    static bool less(Value a,Value b) {return false;}
70 74
    ///Returns \c true if \c a is \e surely different from \c b
71 75
    static bool different(Value a,Value b) {return false;}
72 76
    ///Returns \c true if \c a is \e surely positive
73 77
    static bool positive(Value a) {return false;}
74 78
    ///Returns \c true if \c a is \e surely negative
75 79
    static bool negative(Value a) {return false;}
76 80
    ///Returns \c true if \c a is \e surely non-zero
77 81
    static bool nonZero(Value a) {return false;}
... ...
@@ -109,49 +113,49 @@
109 113
    ///Return the epsilon value.
110 114
    Value epsilon() const {return _epsilon;}
111 115
    ///Set the epsilon value.
112 116
    void epsilon(Value e) {_epsilon=e;}
113 117

	
114 118
    ///Return the default epsilon value.
115 119
    static Value defaultEpsilon() {return def_epsilon;}
116 120
    ///Set the default epsilon value.
117 121
    static void defaultEpsilon(Value e) {def_epsilon=e;}
118 122

	
119 123
    ///\name Comparisons
120 124
    ///See class Tolerance for more details.
121 125

	
122 126
    ///@{
123 127

	
124 128
    ///Returns \c true if \c a is \e surely strictly less than \c b
125 129
    bool less(Value a,Value b) const {return a+_epsilon<b;}
126 130
    ///Returns \c true if \c a is \e surely different from \c b
127 131
    bool different(Value a,Value b) const { return less(a,b)||less(b,a); }
128 132
    ///Returns \c true if \c a is \e surely positive
129 133
    bool positive(Value a) const { return _epsilon<a; }
130 134
    ///Returns \c true if \c a is \e surely negative
131 135
    bool negative(Value a) const { return -_epsilon>a; }
132 136
    ///Returns \c true if \c a is \e surely non-zero
133
    bool nonZero(Value a) const { return positive(a)||negative(a); };
137
    bool nonZero(Value a) const { return positive(a)||negative(a); }
134 138

	
135 139
    ///@}
136 140

	
137 141
    ///Returns zero
138 142
    static Value zero() {return 0;}
139 143
  };
140 144

	
141 145
  ///Double specialization of \ref Tolerance.
142 146

	
143 147
  ///Double specialization of \ref Tolerance.
144 148
  ///\sa Tolerance
145 149
  ///\relates Tolerance
146 150
  template<>
147 151
  class Tolerance<double>
148 152
  {
149 153
    static double def_epsilon;
150 154
    double _epsilon;
151 155
  public:
152 156
    ///\e
153 157
    typedef double Value;
154 158

	
155 159
    ///Constructor setting the epsilon tolerance to the default value.
156 160
    Tolerance() : _epsilon(def_epsilon) {}
157 161
    ///Constructor setting the epsilon tolerance.
... ...
@@ -160,49 +164,49 @@
160 164
    ///Return the epsilon value.
161 165
    Value epsilon() const {return _epsilon;}
162 166
    ///Set the epsilon value.
163 167
    void epsilon(Value e) {_epsilon=e;}
164 168

	
165 169
    ///Return the default epsilon value.
166 170
    static Value defaultEpsilon() {return def_epsilon;}
167 171
    ///Set the default epsilon value.
168 172
    static void defaultEpsilon(Value e) {def_epsilon=e;}
169 173

	
170 174
    ///\name Comparisons
171 175
    ///See class Tolerance for more details.
172 176

	
173 177
    ///@{
174 178

	
175 179
    ///Returns \c true if \c a is \e surely strictly less than \c b
176 180
    bool less(Value a,Value b) const {return a+_epsilon<b;}
177 181
    ///Returns \c true if \c a is \e surely different from \c b
178 182
    bool different(Value a,Value b) const { return less(a,b)||less(b,a); }
179 183
    ///Returns \c true if \c a is \e surely positive
180 184
    bool positive(Value a) const { return _epsilon<a; }
181 185
    ///Returns \c true if \c a is \e surely negative
182 186
    bool negative(Value a) const { return -_epsilon>a; }
183 187
    ///Returns \c true if \c a is \e surely non-zero
184
    bool nonZero(Value a) const { return positive(a)||negative(a); };
188
    bool nonZero(Value a) const { return positive(a)||negative(a); }
185 189

	
186 190
    ///@}
187 191

	
188 192
    ///Returns zero
189 193
    static Value zero() {return 0;}
190 194
  };
191 195

	
192 196
  ///Long double specialization of \ref Tolerance.
193 197

	
194 198
  ///Long double specialization of \ref Tolerance.
195 199
  ///\sa Tolerance
196 200
  ///\relates Tolerance
197 201
  template<>
198 202
  class Tolerance<long double>
199 203
  {
200 204
    static long double def_epsilon;
201 205
    long double _epsilon;
202 206
  public:
203 207
    ///\e
204 208
    typedef long double Value;
205 209

	
206 210
    ///Constructor setting the epsilon tolerance to the default value.
207 211
    Tolerance() : _epsilon(def_epsilon) {}
208 212
    ///Constructor setting the epsilon tolerance.
... ...
@@ -211,244 +215,244 @@
211 215
    ///Return the epsilon value.
212 216
    Value epsilon() const {return _epsilon;}
213 217
    ///Set the epsilon value.
214 218
    void epsilon(Value e) {_epsilon=e;}
215 219

	
216 220
    ///Return the default epsilon value.
217 221
    static Value defaultEpsilon() {return def_epsilon;}
218 222
    ///Set the default epsilon value.
219 223
    static void defaultEpsilon(Value e) {def_epsilon=e;}
220 224

	
221 225
    ///\name Comparisons
222 226
    ///See class Tolerance for more details.
223 227

	
224 228
    ///@{
225 229

	
226 230
    ///Returns \c true if \c a is \e surely strictly less than \c b
227 231
    bool less(Value a,Value b) const {return a+_epsilon<b;}
228 232
    ///Returns \c true if \c a is \e surely different from \c b
229 233
    bool different(Value a,Value b) const { return less(a,b)||less(b,a); }
230 234
    ///Returns \c true if \c a is \e surely positive
231 235
    bool positive(Value a) const { return _epsilon<a; }
232 236
    ///Returns \c true if \c a is \e surely negative
233 237
    bool negative(Value a) const { return -_epsilon>a; }
234 238
    ///Returns \c true if \c a is \e surely non-zero
235
    bool nonZero(Value a) const { return positive(a)||negative(a); };
239
    bool nonZero(Value a) const { return positive(a)||negative(a); }
236 240

	
237 241
    ///@}
238 242

	
239 243
    ///Returns zero
240 244
    static Value zero() {return 0;}
241 245
  };
242 246

	
243 247
  ///Integer specialization of \ref Tolerance.
244 248

	
245 249
  ///Integer specialization of \ref Tolerance.
246 250
  ///\sa Tolerance
247 251
  template<>
248 252
  class Tolerance<int>
249 253
  {
250 254
  public:
251 255
    ///\e
252 256
    typedef int Value;
253 257

	
254 258
    ///\name Comparisons
255 259
    ///See \ref Tolerance for more details.
256 260

	
257 261
    ///@{
258 262

	
259 263
    ///Returns \c true if \c a is \e surely strictly less than \c b
260 264
    static bool less(Value a,Value b) { return a<b;}
261 265
    ///Returns \c true if \c a is \e surely different from \c b
262 266
    static bool different(Value a,Value b) { return a!=b; }
263 267
    ///Returns \c true if \c a is \e surely positive
264 268
    static bool positive(Value a) { return 0<a; }
265 269
    ///Returns \c true if \c a is \e surely negative
266 270
    static bool negative(Value a) { return 0>a; }
267 271
    ///Returns \c true if \c a is \e surely non-zero
268
    static bool nonZero(Value a) { return a!=0; };
272
    static bool nonZero(Value a) { return a!=0; }
269 273

	
270 274
    ///@}
271 275

	
272 276
    ///Returns zero
273 277
    static Value zero() {return 0;}
274 278
  };
275 279

	
276 280
  ///Unsigned integer specialization of \ref Tolerance.
277 281

	
278 282
  ///Unsigned integer specialization of \ref Tolerance.
279 283
  ///\sa Tolerance
280 284
  template<>
281 285
  class Tolerance<unsigned int>
282 286
  {
283 287
  public:
284 288
    ///\e
285 289
    typedef unsigned int Value;
286 290

	
287 291
    ///\name Comparisons
288 292
    ///See \ref Tolerance for more details.
289 293

	
290 294
    ///@{
291 295

	
292 296
    ///Returns \c true if \c a is \e surely strictly less than \c b
293 297
    static bool less(Value a,Value b) { return a<b;}
294 298
    ///Returns \c true if \c a is \e surely different from \c b
295 299
    static bool different(Value a,Value b) { return a!=b; }
296 300
    ///Returns \c true if \c a is \e surely positive
297 301
    static bool positive(Value a) { return 0<a; }
298 302
    ///Returns \c true if \c a is \e surely negative
299 303
    static bool negative(Value) { return false; }
300 304
    ///Returns \c true if \c a is \e surely non-zero
301
    static bool nonZero(Value a) { return a!=0; };
305
    static bool nonZero(Value a) { return a!=0; }
302 306

	
303 307
    ///@}
304 308

	
305 309
    ///Returns zero
306 310
    static Value zero() {return 0;}
307 311
  };
308 312
  
309 313

	
310 314
  ///Long integer specialization of \ref Tolerance.
311 315

	
312 316
  ///Long integer specialization of \ref Tolerance.
313 317
  ///\sa Tolerance
314 318
  template<>
315 319
  class Tolerance<long int>
316 320
  {
317 321
  public:
318 322
    ///\e
319 323
    typedef long int Value;
320 324

	
321 325
    ///\name Comparisons
322 326
    ///See \ref Tolerance for more details.
323 327

	
324 328
    ///@{
325 329

	
326 330
    ///Returns \c true if \c a is \e surely strictly less than \c b
327 331
    static bool less(Value a,Value b) { return a<b;}
328 332
    ///Returns \c true if \c a is \e surely different from \c b
329 333
    static bool different(Value a,Value b) { return a!=b; }
330 334
    ///Returns \c true if \c a is \e surely positive
331 335
    static bool positive(Value a) { return 0<a; }
332 336
    ///Returns \c true if \c a is \e surely negative
333 337
    static bool negative(Value a) { return 0>a; }
334 338
    ///Returns \c true if \c a is \e surely non-zero
335
    static bool nonZero(Value a) { return a!=0;};
339
    static bool nonZero(Value a) { return a!=0;}
336 340

	
337 341
    ///@}
338 342

	
339 343
    ///Returns zero
340 344
    static Value zero() {return 0;}
341 345
  };
342 346

	
343 347
  ///Unsigned long integer specialization of \ref Tolerance.
344 348

	
345 349
  ///Unsigned long integer specialization of \ref Tolerance.
346 350
  ///\sa Tolerance
347 351
  template<>
348 352
  class Tolerance<unsigned long int>
349 353
  {
350 354
  public:
351 355
    ///\e
352 356
    typedef unsigned long int Value;
353 357

	
354 358
    ///\name Comparisons
355 359
    ///See \ref Tolerance for more details.
356 360

	
357 361
    ///@{
358 362

	
359 363
    ///Returns \c true if \c a is \e surely strictly less than \c b
360 364
    static bool less(Value a,Value b) { return a<b;}
361 365
    ///Returns \c true if \c a is \e surely different from \c b
362 366
    static bool different(Value a,Value b) { return a!=b; }
363 367
    ///Returns \c true if \c a is \e surely positive
364 368
    static bool positive(Value a) { return 0<a; }
365 369
    ///Returns \c true if \c a is \e surely negative
366 370
    static bool negative(Value) { return false; }
367 371
    ///Returns \c true if \c a is \e surely non-zero
368
    static bool nonZero(Value a) { return a!=0;};
372
    static bool nonZero(Value a) { return a!=0;}
369 373

	
370 374
    ///@}
371 375

	
372 376
    ///Returns zero
373 377
    static Value zero() {return 0;}
374 378
  };
375 379

	
376 380
#if defined __GNUC__ && !defined __STRICT_ANSI__
377 381

	
378 382
  ///Long long integer specialization of \ref Tolerance.
379 383

	
380 384
  ///Long long integer specialization of \ref Tolerance.
381 385
  ///\warning This class (more exactly, type <tt>long long</tt>)
382 386
  ///is not ansi compatible.
383 387
  ///\sa Tolerance
384 388
  template<>
385 389
  class Tolerance<long long int>
386 390
  {
387 391
  public:
388 392
    ///\e
389 393
    typedef long long int Value;
390 394

	
391 395
    ///\name Comparisons
392 396
    ///See \ref Tolerance for more details.
393 397

	
394 398
    ///@{
395 399

	
396 400
    ///Returns \c true if \c a is \e surely strictly less than \c b
397 401
    static bool less(Value a,Value b) { return a<b;}
398 402
    ///Returns \c true if \c a is \e surely different from \c b
399 403
    static bool different(Value a,Value b) { return a!=b; }
400 404
    ///Returns \c true if \c a is \e surely positive
401 405
    static bool positive(Value a) { return 0<a; }
402 406
    ///Returns \c true if \c a is \e surely negative
403 407
    static bool negative(Value a) { return 0>a; }
404 408
    ///Returns \c true if \c a is \e surely non-zero
405
    static bool nonZero(Value a) { return a!=0;};
409
    static bool nonZero(Value a) { return a!=0;}
406 410

	
407 411
    ///@}
408 412

	
409 413
    ///Returns zero
410 414
    static Value zero() {return 0;}
411 415
  };
412 416

	
413 417
  ///Unsigned long long integer specialization of \ref Tolerance.
414 418

	
415 419
  ///Unsigned long long integer specialization of \ref Tolerance.
416 420
  ///\warning This class (more exactly, type <tt>unsigned long long</tt>)
417 421
  ///is not ansi compatible.
418 422
  ///\sa Tolerance
419 423
  template<>
420 424
  class Tolerance<unsigned long long int>
421 425
  {
422 426
  public:
423 427
    ///\e
424 428
    typedef unsigned long long int Value;
425 429

	
426 430
    ///\name Comparisons
427 431
    ///See \ref Tolerance for more details.
428 432

	
429 433
    ///@{
430 434

	
431 435
    ///Returns \c true if \c a is \e surely strictly less than \c b
432 436
    static bool less(Value a,Value b) { return a<b;}
433 437
    ///Returns \c true if \c a is \e surely different from \c b
434 438
    static bool different(Value a,Value b) { return a!=b; }
435 439
    ///Returns \c true if \c a is \e surely positive
436 440
    static bool positive(Value a) { return 0<a; }
437 441
    ///Returns \c true if \c a is \e surely negative
438 442
    static bool negative(Value) { return false; }
439 443
    ///Returns \c true if \c a is \e surely non-zero
440
    static bool nonZero(Value a) { return a!=0;};
444
    static bool nonZero(Value a) { return a!=0;}
441 445

	
442 446
    ///@}
443 447

	
444 448
    ///Returns zero
445 449
    static Value zero() {return 0;}
446 450
  };
447 451

	
448 452
#endif
449 453

	
450 454
  /// @}
451 455

	
452 456
} //namespace lemon
453 457

	
454 458
#endif //LEMON_TOLERANCE_H
Ignore white space 6 line context
1 1
EXTRA_DIST += \
2 2
	test/Makefile
3 3

	
4 4
noinst_HEADERS += \
5 5
        test/test_tools.h
6
 
6

	
7 7
check_PROGRAMS += \
8 8
        test/dim_test \
9
        test/random_test \
9 10
        test/test_tools_fail \
10 11
        test/test_tools_pass
11
 
12

	
12 13
TESTS += $(check_PROGRAMS)
13 14
XFAIL_TESTS += test/test_tools_fail$(EXEEXT)
14 15

	
15 16
test_dim_test_SOURCES = test/dim_test.cc
17
test_random_test_SOURCES = test/random_test.cc
16 18
test_test_tools_fail_SOURCES = test/test_tools_fail.cc
17 19
test_test_tools_pass_SOURCES = test/test_tools_pass.cc
Ignore white space 6 line context
1 1
/* -*- C++ -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library
4 4
 *
5 5
 * Copyright (C) 2003-2007
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#include <lemon/dim2.h>
20 20
#include <iostream>
21 21
#include "test_tools.h"
22 22

	
23 23
using namespace std;
24 24
using namespace lemon;
25

	
25 26
int main()
26 27
{
27

	
28
  cout << "Testing classes `dim2::Point' and `dim2::BoundingBox'." << endl;
28
  cout << "Testing classes 'dim2::Point' and 'dim2::BoundingBox'." << endl;
29 29

	
30 30
  typedef dim2::Point<int> Point;
31
	
32
  Point seged;
33
  check(seged.size()==2, "Wrong vector addition");
31

	
32
  Point p;
33
  check(p.size()==2, "Wrong vector initialization.");
34 34

	
35 35
  Point a(1,2);
36 36
  Point b(3,4);
37
  check(a[0]==1 && a[1]==2, "Wrong vector initialization.");
37 38

	
38
  check(a[0]==1 && a[1]==2, "Wrong vector addition");
39
  p = a+b;
40
  check(p.x==4 && p.y==6, "Wrong vector addition.");
39 41

	
40
  seged = a+b;
41
  check(seged.x==4 && seged.y==6, "Wrong vector addition");
42
  p = a-b;
43
  check(p.x==-2 && p.y==-2, "Wrong vector subtraction.");
42 44

	
43
  seged = a-b;
44
  check(seged.x==-2 && seged.y==-2, "a-b");
45

	
46
  check(a.normSquare()==5,"Wrong norm calculation");
47
  check(a*b==11, "a*b");
45
  check(a.normSquare()==5,"Wrong vector norm calculation.");
46
  check(a*b==11, "Wrong vector scalar product.");
48 47

	
49 48
  int l=2;
50
  seged = a*l;
51
  check(seged.x==2 && seged.y==4, "a*l");
49
  p = a*l;
50
  check(p.x==2 && p.y==4, "Wrong vector multiplication by a scalar.");
52 51

	
53
  seged = b/l;
54
  check(seged.x==1 && seged.y==2, "b/l");
52
  p = b/l;
53
  check(p.x==1 && p.y==2, "Wrong vector division by a scalar.");
55 54

	
56 55
  typedef dim2::BoundingBox<int> BB;
57
  BB doboz1;
58
  check(doboz1.empty(), "It should be empty.");
59
	
60
  doboz1.add(a);
61
  check(!doboz1.empty(), "It should not be empty.");
62
  doboz1.add(b);
56
  BB box1;
57
  check(box1.empty(), "It should be empty.");
63 58

	
64
  check(doboz1.bottomLeft().x==1 && 
65
        doboz1.bottomLeft().y==2 &&
66
        doboz1.topRight().x==3 && 
67
        doboz1.topRight().y==4,  
68
        "added points to box");
59
  box1.add(a);
60
  check(!box1.empty(), "It should not be empty.");
61
  box1.add(b);
69 62

	
70
  seged.x=2;seged.y=3;
71
  check(doboz1.inside(seged),"It should be inside.");
63
  check(box1.bottomLeft().x==1 &&
64
        box1.bottomLeft().y==2 &&
65
        box1.topRight().x==3 &&
66
        box1.topRight().y==4,
67
        "Wrong addition of points to box.");
72 68

	
73
  seged.x=1;seged.y=3;
74
  check(doboz1.inside(seged),"It should be inside.");
69
  p.x=2; p.y=3;
70
  check(box1.inside(p), "It should be inside.");
75 71

	
76
  seged.x=0;seged.y=3;
77
  check(!doboz1.inside(seged),"It should not be inside.");
72
  p.x=1; p.y=3;
73
  check(box1.inside(p), "It should be inside.");
78 74

	
79
  BB doboz2(seged);
80
  check(!doboz2.empty(),
75
  p.x=0; p.y=3;
76
  check(!box1.inside(p), "It should not be inside.");
77

	
78
  BB box2(p);
79
  check(!box2.empty(),
81 80
        "It should not be empty. Constructed from 1 point.");
82 81

	
83
  doboz2.add(doboz1);
84
  check(doboz2.inside(seged),
82
  box2.add(box1);
83
  check(box2.inside(p),
85 84
        "It should be inside. Incremented a box with another one.");
85

	
86
  return 0;
86 87
}
0 comments (0 inline)