1 package org.djutils.math.functions;
2
3 import java.util.Objects;
4 import java.util.SortedSet;
5 import java.util.TreeSet;
6
7 import org.djutils.exceptions.Throw;
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 public class Constant implements MathFunction
23 {
24
25 private final double value;
26
27
28 public static final Constant ZERO = new Constant(0.0);
29
30
31 public static final Constant ONE = new Constant(1.0);
32
33
34
35
36
37 public Constant(final double value)
38 {
39 this.value = value;
40 }
41
42 @Override
43 public double get(final double x)
44 {
45 return this.value;
46 }
47
48 @Override
49 public Constant getDerivative()
50 {
51 return ZERO;
52 }
53
54 @Override
55 public MathFunction simplify()
56 {
57 if (this.value == ZERO.value)
58 {
59 return ZERO;
60 }
61 if (this.value == ONE.value)
62 {
63 return ONE;
64 }
65 return this;
66 }
67
68 @Override
69 public double getScale()
70 {
71 return this.value;
72 }
73
74 @Override
75 public MathFunction scaleBy(final double factor)
76 {
77 return new Constant(factor * this.value).simplify();
78 }
79
80 @Override
81 public int sortPriority()
82 {
83 return 2;
84 }
85
86 @Override
87 public int compareWithinSubType(final MathFunction other)
88 {
89 Throw.when(!(other instanceof Constant), IllegalArgumentException.class, "other is of wrong type");
90 Constant otherConstant = (Constant) other;
91 if (this.value < otherConstant.value)
92 {
93 return -1;
94 }
95 if (this.value > otherConstant.value)
96 {
97 return 1;
98 }
99 return 0;
100 }
101
102 @Override
103 public MathFunction mergeAdd(final MathFunction other)
104 {
105 if (other instanceof Constant)
106 {
107 double total = this.value + ((Constant) other).value;
108 return new Constant(total).simplify();
109 }
110 return null;
111 }
112
113 @Override
114 public MathFunction mergeMultiply(final MathFunction other)
115 {
116 if (other instanceof Constant)
117 {
118 double product = this.value * ((Constant) other).value;
119 return new Constant(product).simplify();
120 }
121 return null;
122 }
123
124 @Override
125 public KnotReport getKnotReport(final Interval<?> interval)
126 {
127 return KnotReport.NONE;
128 }
129
130 @Override
131 public SortedSet<Double> getKnots(final Interval<?> interval)
132 {
133 return new TreeSet<Double>();
134 }
135
136 @Override
137 public String toString()
138 {
139 return printValue(this.value);
140 }
141
142 @Override
143 public int hashCode()
144 {
145 return Objects.hash(this.value);
146 }
147
148 @SuppressWarnings("checkstyle:needbraces")
149 @Override
150 public boolean equals(final Object obj)
151 {
152 if (this == obj)
153 return true;
154 if (obj == null)
155 return false;
156 if (getClass() != obj.getClass())
157 return false;
158 Constant other = (Constant) obj;
159 return Double.doubleToLongBits(this.value) == Double.doubleToLongBits(other.value);
160 }
161
162 }