1 package nl.tudelft.simulation.jstats.distributions;
2
3 import org.djutils.exceptions.Throw;
4
5 import nl.tudelft.simulation.jstats.streams.StreamInterface;
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 public class DistTriangular extends DistContinuous
22 {
23
24 private static final long serialVersionUID = 1L;
25
26
27 private final double min;
28
29
30 private final double mode;
31
32
33 private final double max;
34
35
36
37
38
39
40
41
42
43 public DistTriangular(final StreamInterface stream, final double min, final double mode, final double max)
44 {
45 super(stream);
46 Throw.when(mode < min || mode > max || min == max, IllegalArgumentException.class,
47 "Triangular distribution, mode < min or mode > max or min == max");
48 this.min = min;
49 this.mode = mode;
50 this.max = max;
51 }
52
53
54 @Override
55 public double draw()
56 {
57 double u = this.stream.nextDouble();
58 if (u <= ((this.mode - this.min) / (this.max - this.min)))
59 {
60 return this.min + Math.sqrt((this.mode - this.min) * (this.max - this.min) * u);
61 }
62 return this.max - Math.sqrt((this.max - this.min) * (this.max - this.mode) * (1.0d - u));
63 }
64
65
66 @Override
67 public double getProbabilityDensity(final double x)
68 {
69 if (x >= this.min && x <= this.mode)
70 {
71 return 2.0 * (x - this.min) / ((this.max - this.min) * (this.mode - this.min));
72 }
73 if (x >= this.mode && x <= this.max)
74 {
75 return 2.0 * (this.max - x) / ((this.max - this.min) * (this.max - this.mode));
76 }
77 return 0.0;
78 }
79
80
81
82
83
84 public double getMin()
85 {
86 return this.min;
87 }
88
89
90
91
92
93 public double getMode()
94 {
95 return this.mode;
96 }
97
98
99
100
101
102 public double getMax()
103 {
104 return this.max;
105 }
106
107
108 @Override
109 public String toString()
110 {
111 return "Triangular(" + this.min + "," + this.mode + "," + this.max + ")";
112 }
113 }