summaryrefslogtreecommitdiff
path: root/src/main/java/sevenUnits/unit/LinearUnitValue.java
blob: ce60e3b39b64c6676f2c15bbb3d26cd97c512946 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/**
 * Copyright (C) 2019, 2021, 2022, 2024, 2025 Adrien Hopkins
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
package sevenUnits.unit;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import sevenUnits.utils.DecimalComparison;
import sevenUnits.utils.ObjectProduct;
import sevenUnits.utils.UncertainDouble;

/**
 * A possibly uncertain value expressed in a linear unit.
 *
 * Unless otherwise indicated, all methods in this class throw a
 * {@code NullPointerException} when an argument is null.
 *
 * @author Adrien Hopkins
 * @since 2020-07-26
 * @since v0.3.0
 */
public final class LinearUnitValue {
	/** The value 1 as a LinearUnitValue. */
	public static final LinearUnitValue ONE = getExact(Metric.ONE, 1);

	/**
	 * Gets an exact {@code LinearUnitValue}
	 *
	 * @param unit  unit to express with
	 * @param value value to express
	 * @return exact {@code LinearUnitValue} instance
	 * @since 2020-07-26
	 * @since v0.3.0
	 */
	public static LinearUnitValue getExact(final LinearUnit unit,
			final double value) {
		return new LinearUnitValue(
				Objects.requireNonNull(unit, "unit must not be null"),
				UncertainDouble.of(value, 0));
	}

	/**
	 * Gets an uncertain {@code LinearUnitValue}
	 *
	 * @param unit  unit to express with
	 * @param value value to express
	 * @return uncertain {@code LinearUnitValue} instance
	 * @since 2020-07-26
	 * @since v0.3.0
	 */
	public static LinearUnitValue of(final LinearUnit unit,
			final UncertainDouble value) {
		return new LinearUnitValue(
				Objects.requireNonNull(unit, "unit must not be null"),
				Objects.requireNonNull(value, "value may not be null"));
	}

	private final LinearUnit unit;

	private final UncertainDouble value;

	/**
	 * @param unit  unit to express as
	 * @param value value to express
	 * @since 2020-07-26
	 * @since v0.3.0
	 */
	private LinearUnitValue(final LinearUnit unit, final UncertainDouble value) {
		this.unit = unit;
		this.value = value;
	}

	/**
	 * @return this value as a {@code UnitValue}. All uncertainty information is
	 *         removed from the returned value.
	 * @since 2020-08-04
	 * @since v0.3.0
	 */
	public UnitValue asUnitValue() {
		return UnitValue.of(this.unit, this.value.value());
	}

	/**
	 * @param other a {@code LinearUnit}
	 * @return true iff this value can be represented with {@code other}.
	 * @since 2020-07-26
	 * @since v0.3.0
	 */
	public boolean canConvertTo(final LinearUnit other) {
		return this.unit.canConvertTo(other);
	}

	/**
	 * Returns a LinearUnitValue that represents the same value expressed in a
	 * different unit
	 *
	 * @param other new unit to express value in
	 * @return value expressed in {@code other}
	 * @since 2020-07-26
	 * @since v0.3.0
	 */
	public LinearUnitValue convertTo(final LinearUnit other) {
		return LinearUnitValue.of(other, this.unit.convertTo(other, this.value));
	}

	/**
	 * Convert a LinearUnitValue to a sum of multiple units, where all but the
	 * last have exact integer values.
	 *
	 * @param others units to convert to
	 * @return terms of the sum
	 * @throws IllegalArgumentException if no units are provided or units
	 *                                  provided have incompatible bases
	 * @since 2024-08-15
	 * @since v1.0.0
	 */
	public List<LinearUnitValue> convertToMultiple(
			final List<LinearUnit> others) {
		if (others.size() < 1)
			throw new IllegalArgumentException("Must have at least one unit");
		for (final LinearUnit unit : others) {
			if (!Objects.equals(this.unit.getBase(), unit.getBase()))
				throw new IllegalArgumentException(
						"All provided units must have the same base as the value.");
		}

		var remaining = this;
		final List<LinearUnitValue> values = new ArrayList<>(others.size());
		for (final LinearUnit unit : others.subList(0, others.size() - 1)) {
			final var remainingInUnit = remaining.convertTo(unit);
			final var value = getExact(unit,
					Math.floor(remainingInUnit.getValueExact() + 1e-12));
			values.add(value);
			remaining = remaining.minus(value);
		}

		final var lastValue = remaining.convertTo(others.get(others.size() - 1));
		values.add(lastValue);
		return values;
	}

	/**
	 * Divides this value by a scalar
	 *
	 * @param divisor value to divide by
	 * @return multiplied value
	 * @since 2020-07-28
	 * @since v0.3.0
	 */
	public LinearUnitValue dividedBy(final double divisor) {
		return LinearUnitValue.of(this.unit, this.value.dividedByExact(divisor));
	}

	/**
	 * Divides this value by another value
	 *
	 * @param divisor value to multiply by
	 * @return quotient
	 * @since 2020-07-28
	 * @since v0.3.0
	 */
	public LinearUnitValue dividedBy(final LinearUnitValue divisor) {
		return LinearUnitValue.of(this.unit.dividedBy(divisor.unit),
				this.value.dividedBy(divisor.value));
	}

	/**
	 * Returns true if this and obj represent the same value, regardless of
	 * whether or not they are expressed in the same unit. So (1000 m).equals(1
	 * km) returns true.
	 *
	 * @since 2020-07-26
	 * @since v0.3.0
	 * @see #equals(Object, boolean)
	 */
	@Override
	public boolean equals(final Object obj) {
		if (!(obj instanceof LinearUnitValue))
			return false;
		final var other = (LinearUnitValue) obj;
		return Objects.equals(this.unit.getBase(), other.unit.getBase())
				&& this.unit.convertToBase(this.value)
						.equals(other.unit.convertToBase(other.value));
	}

	/**
	 * Returns true if this and obj represent the same value, regardless of
	 * whether or not they are expressed in the same unit. So (1000 m).equals(1
	 * km) returns true.
	 *
	 * @param obj           object to test equality with
	 * @param avoidFPErrors if true, this method will attempt to avoid
	 *                      floating-point errors, at the cost of not always
	 *                      being transitive.
	 * @return true iff this and obj are equal
	 *
	 * @since 2020-07-28
	 * @since v0.3.0
	 */
	public boolean equals(final Object obj, final boolean avoidFPErrors) {
		if (!avoidFPErrors)
			return this.equals(obj);
		if (!(obj instanceof LinearUnitValue))
			return false;
		final var other = (LinearUnitValue) obj;
		return Objects.equals(this.unit.getBase(), other.unit.getBase())
				&& DecimalComparison.equals(this.unit.convertToBase(this.value),
						other.unit.convertToBase(other.value));
	}

	/**
	 * @param other another {@code LinearUnitValue}
	 * @return true iff this and other are within each other's uncertainty range
	 *
	 * @since 2020-07-26
	 * @since v0.3.0
	 */
	public boolean equivalent(final LinearUnitValue other) {
		if (other == null
				|| !Objects.equals(this.unit.getBase(), other.unit.getBase()))
			return false;
		final var base = LinearUnit.valueOf(this.unit.getBase(), 1);
		final var thisBase = this.convertTo(base);
		final var otherBase = other.convertTo(base);

		return thisBase.value.equivalent(otherBase.value);
	}

	/**
	 * @return the unit
	 * @since 2020-09-29
	 * @since v0.3.0
	 */
	public LinearUnit getUnit() {
		return this.unit;
	}

	/**
	 * @return the value
	 * @since 2020-09-29
	 * @since v0.3.0
	 */
	public UncertainDouble getValue() {
		return this.value;
	}

	/**
	 * @return the exact value
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public double getValueExact() {
		return this.value.value();
	}

	@Override
	public int hashCode() {
		return Objects.hash(this.unit.getBase(),
				this.unit.convertToBase(this.getValue()));
	}

	/**
	 * Returns the difference of this value and another, expressed in this
	 * value's unit
	 *
	 * @param subtrahend value to subtract
	 * @return difference of values
	 * @throws IllegalArgumentException if {@code subtrahend} has a unit that is
	 *                                  not compatible for addition
	 * @since 2020-07-26
	 * @since v0.3.0
	 */
	public LinearUnitValue minus(final LinearUnitValue subtrahend) {
		Objects.requireNonNull(subtrahend, "subtrahend may not be null");

		if (!this.canConvertTo(subtrahend.unit))
			throw new IllegalArgumentException(String.format(
					"Incompatible units for subtraction \"%s\" and \"%s\".",
					this.unit, subtrahend.unit));

		final var otherConverted = subtrahend.convertTo(this.unit);
		return LinearUnitValue.of(this.unit,
				this.value.minus(otherConverted.value));
	}

	/**
	 * Returns the sum of this value and another, expressed in this value's unit
	 *
	 * @param addend value to add
	 * @return sum of values
	 * @throws IllegalArgumentException if {@code addend} has a unit that is not
	 *                                  compatible for addition
	 * @since 2020-07-26
	 * @since v0.3.0
	 */
	public LinearUnitValue plus(final LinearUnitValue addend) {
		Objects.requireNonNull(addend, "addend may not be null");

		if (!this.canConvertTo(addend.unit))
			throw new IllegalArgumentException(String.format(
					"Incompatible units for addition \"%s\" and \"%s\".", this.unit,
					addend.unit));

		final var otherConverted = addend.convertTo(this.unit);
		return LinearUnitValue.of(this.unit,
				this.value.plus(otherConverted.value));
	}

	/**
	 * Multiplies this value by a scalar
	 *
	 * @param multiplier value to multiply by
	 * @return multiplied value
	 * @since 2020-07-28
	 * @since v0.3.0
	 */
	public LinearUnitValue times(final double multiplier) {
		return LinearUnitValue.of(this.unit, this.value.timesExact(multiplier));
	}

	/**
	 * Multiplies this value by another value
	 *
	 * @param multiplier value to multiply by
	 * @return product
	 * @since 2020-07-28
	 * @since v0.3.0
	 */
	public LinearUnitValue times(final LinearUnitValue multiplier) {
		return LinearUnitValue.of(this.unit.times(multiplier.unit),
				this.value.times(multiplier.value));
	}

	/**
	 * Raises a value to an exponent
	 *
	 * @param exponent exponent to raise to
	 * @return result of exponentiation
	 * @since 2020-07-28
	 * @since v0.3.0
	 */
	public LinearUnitValue toExponent(final int exponent) {
		return LinearUnitValue.of(this.unit.toExponent(exponent),
				this.value.toExponentExact(exponent));
	}

	/**
	 * Raises this value to an exponent, rounding all dimensions to integers.
	 *
	 * @param exponent exponent to raise this value to
	 * @return result of exponentation
	 *
	 * @since 2024-08-22
	 * @since v1.0.0
	 * @see ObjectProduct#toExponentRounded
	 */
	public LinearUnitValue toExponentRounded(final double exponent) {
		return LinearUnitValue.of(this.unit.toExponentRounded(exponent),
				this.value.toExponentExact(exponent));
	}

	@Override
	public String toString() {
		return this.toString(!this.value.isExact(), RoundingMode.HALF_EVEN);
	}

	/**
	 * Returns a string representing the object. <br>
	 * If the attached unit has a name or symbol, the string looks like "12 km".
	 * Otherwise, it looks like "13 unnamed unit (= 2 m/s)".
	 * <p>
	 * If showUncertainty is true, strings like "35 � 8" are shown instead of
	 * single numbers.
	 * <p>
	 * Non-exact values are rounded intelligently based on their uncertainty.
	 *
	 * @param showUncertainty whether to show the value's uncertainty
	 * @param roundingMode    how to round numbers in this string
	 * @return string representing this value
	 *
	 * @since 2020-07-26
	 * @since v0.3.0
	 */
	public String toString(final boolean showUncertainty,
			RoundingMode roundingMode) {
		final var primaryName = this.unit.getPrimaryName();
		final var symbol = this.unit.getSymbol();
		final var chosenName = symbol.orElse(primaryName.orElse(null));

		final var baseValue = this.unit.convertToBase(this.value);

		// get rounded strings
		// if showUncertainty is true, add brackets around the string
		final var valueString = (showUncertainty ? "(" : "")
				+ this.value.toString(showUncertainty, roundingMode)
				+ (showUncertainty ? ")" : "");
		final var baseValueString = (showUncertainty ? "(" : "")
				+ baseValue.toString(showUncertainty, roundingMode)
				+ (showUncertainty ? ")" : "");

		// create string
		if (chosenName == null)
			return String.format("%s unnamed unit (= %s %s)", valueString,
					baseValueString, this.unit.getBase()
							.toString(unit -> unit.getSymbol().orElseThrow()));
		return String.format("%s %s", valueString, chosenName);
	}
}