summaryrefslogtreecommitdiff
path: root/src/main/java/sevenUnits/utils/UncertainDouble.java
blob: ecee58664df33dc1d6594b055f7917784a1e75e1 (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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
/**
 * Copyright (C) 2020-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.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * A double with an associated uncertainty value. For example, 3.2 � 0.2.
 * <p>
 * All methods in this class throw a NullPointerException if any of their
 * arguments is null.
 *
 * @since 2020-09-07
 * @since v0.3.0
 */
public final class UncertainDouble implements Comparable<UncertainDouble> {
	/** The exact value 0 */
	public static final UncertainDouble ZERO = UncertainDouble.of(0, 0);

	static final String NUMBER_REGEX = "(\\d+(?:[\\.,]\\d+))";

	/** A regular expression that can recognize toString forms */
	static final Pattern TO_STRING = Pattern.compile(NUMBER_REGEX
			// optional "± [number]"
			+ "(?:\\s*(?:±|\\+-)\\s*" + NUMBER_REGEX + ")?");

	/**
	 * Gets an UncertainDouble from a double string. The uncertainty of the
	 * double will be one of the lowest decimal place of the number. For example,
	 * "12345.678" will become 12345.678 ± 0.001.
	 *
	 * @param s string to parse
	 * @return parsed {@code UncertainDouble}
	 *
	 * @throws NumberFormatException if the argument is not a number
	 *
	 * @since 2022-04-18
	 * @since v0.4.0
	 */
	public static UncertainDouble fromRoundedString(String s) {
		final var value = new BigDecimal(s);
		final var uncertainty = Math.pow(10, -value.scale());
		return UncertainDouble.of(value.doubleValue(), uncertainty);
	}

	/**
	 * Parses a string in the form of
	 * {@link UncertainDouble#toString(boolean, RoundingMode)} and returns the
	 * corresponding {@code UncertainDouble} instance.
	 * <p>
	 * This method allows some alternative forms of the string representation,
	 * such as using "+-" instead of "±".
	 *
	 * @param s string to parse
	 * @return {@code UncertainDouble} instance
	 * @throws IllegalArgumentException if the string is invalid
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public static UncertainDouble fromString(String s) {
		Objects.requireNonNull(s, "s may not be null");
		final var matcher = TO_STRING.matcher(s);

		if (!matcher.matches())
			throw new IllegalArgumentException(
					"Could not parse string \"" + s + "\".");

		double value, uncertainty;
		try {
			value = Double.parseDouble(matcher.group(1));
		} catch (final NumberFormatException e) {
			throw new IllegalArgumentException(
					"String " + s + " not in correct format.");
		}

		final var uncertaintyString = matcher.group(2);
		if (uncertaintyString == null) {
			uncertainty = 0;
		} else {
			try {
				uncertainty = Double.parseDouble(uncertaintyString);
			} catch (final NumberFormatException e) {
				throw new IllegalArgumentException(
						"String " + s + " not in correct format.");
			}
		}

		return UncertainDouble.of(value, uncertainty);
	}

	/**
	 * Gets an {@code UncertainDouble} from its value and <b>absolute</b>
	 * uncertainty.
	 *
	 * @param value       double's value
	 * @param uncertainty double's uncertainty (non-negative)
	 * @return {@code UncertainDouble} instance with these parameters
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public static UncertainDouble of(double value, double uncertainty) {
		return new UncertainDouble(value, uncertainty);
	}

	/**
	 * Gets an {@code UncertainDouble} from its value and <b>relative</b>
	 * uncertainty.
	 *
	 * @param value               double's value
	 * @param relativeUncertainty double's uncertainty (non-negative); the
	 *                            absolute uncertainty is equal to this value
	 *                            multiplied by {@code relativeUncertainty}
	 * @return {@code UncertainDouble} instance with these parameters
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public static UncertainDouble ofRelative(double value,
			double relativeUncertainty) {
		return new UncertainDouble(value, value * relativeUncertainty);
	}

	private final double value;

	private final double uncertainty;

	/**
	 * @param value
	 * @param uncertainty
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	private UncertainDouble(double value, double uncertainty) {
		this.value = value;
		// uncertainty should only ever be positive
		this.uncertainty = Math.abs(uncertainty);
	}

	/**
	 * Compares this {@code UncertainDouble} with another
	 * {@code UncertainDouble}.
	 * <p>
	 * This method only compares the values, not the uncertainties. So 3.1 � 0.5
	 * is considered less than 3.2 � 0.5, even though they are equivalent.
	 * <p>
	 * <b>Note:</b> The natural ordering of this class is inconsistent with
	 * equals. Specifically, if two {@code UncertainDouble} instances {@code a}
	 * and {@code b} have the same value but different uncertainties,
	 * {@code a.compareTo(b)} will return 0 but {@code a.equals(b)} will return
	 * {@code false}.
	 */
	@Override
	public int compareTo(UncertainDouble o) {
		return Double.compare(this.value, o.value);
	}

	/**
	 * Returns the quotient of {@code this} and {@code other}.
	 *
	 * @param other number to divide by
	 * @return quotient
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public UncertainDouble dividedBy(UncertainDouble other) {
		Objects.requireNonNull(other, "other may not be null");
		return UncertainDouble.ofRelative(this.value / other.value, Math
				.hypot(this.relativeUncertainty(), other.relativeUncertainty()));
	}

	/**
	 * Returns the quotient of {@code this} and the exact value {@code other}.
	 *
	 * @param other number to divide by
	 * @return quotient
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public UncertainDouble dividedByExact(double other) {
		return UncertainDouble.of(this.value / other, this.uncertainty / other);
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (!(obj instanceof UncertainDouble))
			return false;
		final var other = (UncertainDouble) obj;
		if ((Double.compare(this.value, other.value) != 0) || (Double.compare(this.uncertainty, other.uncertainty) != 0))
			return false;
		return true;
	}

	/**
	 * @param other another {@code UncertainDouble}
	 * @return true iff this and {@code other} are within each other's
	 *         uncertainty range.
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public boolean equivalent(UncertainDouble other) {
		Objects.requireNonNull(other, "other may not be null");
		return Math.abs(this.value - other.value) <= Math.min(this.uncertainty,
				other.uncertainty);
	}

	/**
	 * Gets the preferred scale for rounding a value for toString.
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	private int getDisplayScale() {
		// round based on uncertainty
		// if uncertainty starts with 1 (ignoring zeroes and the decimal
		// point), rounds
		// so that uncertainty has 2 significant digits.
		// otherwise, rounds so that uncertainty has 1 significant digits.
		// the value is rounded to the same number of decimal places as the
		// uncertainty.
		final var bigUncertainty = BigDecimal.valueOf(this.uncertainty);

		// the scale that will give the uncertainty two decimal places
		final var twoDecimalPlacesScale = bigUncertainty.scale()
				- bigUncertainty.precision() + 2;
		final var roundedUncertainty = bigUncertainty
				.setScale(twoDecimalPlacesScale, RoundingMode.HALF_EVEN);

		if (roundedUncertainty.unscaledValue().intValue() >= 20)
			return twoDecimalPlacesScale - 1; // one decimal place
		return twoDecimalPlacesScale;
	}

	@Override
	public int hashCode() {
		final var prime = 31;
		var result = 1;
		result = prime * result + Double.hashCode(this.value);
		result = prime * result + Double.hashCode(this.uncertainty);
		return result;
	}

	/**
	 * @return true iff the value has no uncertainty
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public boolean isExact() {
		return this.uncertainty == 0;
	}

	/**
	 * Returns the difference of {@code this} and {@code other}.
	 *
	 * @param other number to subtract
	 * @return result of subtraction
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public UncertainDouble minus(UncertainDouble other) {
		Objects.requireNonNull(other, "other may not be null");
		return UncertainDouble.of(this.value - other.value,
				Math.hypot(this.uncertainty, other.uncertainty));
	}

	/**
	 * Returns the difference of {@code this} and the exact value {@code other}.
	 *
	 * @param other number to subtract
	 * @return result of subtraction
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public UncertainDouble minusExact(double other) {
		return UncertainDouble.of(this.value - other, this.uncertainty);
	}

	/**
	 * Returns the sum of {@code this} and {@code other}.
	 *
	 * @param other number to add
	 * @return result of addition
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public UncertainDouble plus(UncertainDouble other) {
		Objects.requireNonNull(other, "other may not be null");
		return UncertainDouble.of(this.value + other.value,
				Math.hypot(this.uncertainty, other.uncertainty));
	}

	/**
	 * Returns the sum of {@code this} and the exact value {@code other}.
	 *
	 * @param other number to add
	 * @return result of addition
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public UncertainDouble plusExact(double other) {
		return UncertainDouble.of(this.value + other, this.uncertainty);
	}

	/**
	 * @return relative uncertainty
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public double relativeUncertainty() {
		return this.uncertainty / this.value;
	}

	/**
	 * Returns the product of {@code this} and {@code other}.
	 *
	 * @param other number to multiply
	 * @return product
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public UncertainDouble times(UncertainDouble other) {
		Objects.requireNonNull(other, "other may not be null");
		return UncertainDouble.ofRelative(this.value * other.value, Math
				.hypot(this.relativeUncertainty(), other.relativeUncertainty()));
	}

	/**
	 * Returns the product of {@code this} and the exact value {@code other}.
	 *
	 * @param other number to multiply
	 * @return product
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public UncertainDouble timesExact(double other) {
		return UncertainDouble.of(this.value * other, this.uncertainty * other);
	}

	/**
	 * Returns the result of {@code this} raised to the exponent {@code other}.
	 *
	 * @param other exponent
	 * @return result of exponentation
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public UncertainDouble toExponent(UncertainDouble other) {
		Objects.requireNonNull(other, "other may not be null");

		final var result = Math.pow(this.value, other.value);
		final var relativeUncertainty = Math.hypot(
				other.value * this.relativeUncertainty(),
				Math.log(this.value) * other.uncertainty);

		return UncertainDouble.ofRelative(result, relativeUncertainty);
	}

	/**
	 * Returns the result of {@code this} raised the exact exponent
	 * {@code other}.
	 *
	 * @param other exponent
	 * @return result of exponentation
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public UncertainDouble toExponentExact(double other) {
		return UncertainDouble.ofRelative(Math.pow(this.value, other),
				this.relativeUncertainty() * other);
	}

	/**
	 * Returns a string representation of this {@code UncertainDouble}.
	 * <p>
	 * This method returns the same value as
	 * {@link #toString(boolean, RoundingMode)}, but {@code showUncertainty} is
	 * true if and only if the uncertainty is non-zero.
	 *
	 * <p>
	 * Examples:
	 *
	 * <pre>
	 * UncertainDouble.of(3.27, 0.22).toString() = "3.3 � 0.2"
	 * UncertainDouble.of(3.27, 0.13).toString() = "3.27 � 0.13"
	 * UncertainDouble.of(-5.01, 0).toString() = "-5.01"
	 * </pre>
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	@Override
	public String toString() {
		return this.toString(!this.isExact(), RoundingMode.HALF_EVEN);
	}

	/**
	 * Returns a string representation of this {@code UncertainDouble}.
	 * <p>
	 * If {@code showUncertainty} is true, the string will be of the form "VALUE
	 * ± UNCERTAINTY", and if it is false the string will be of the form "VALUE"
	 * <p>
	 * VALUE represents a string representation of this {@code UncertainDouble}'s
	 * value. If the uncertainty is non-zero, the string will be rounded to the
	 * same precision as the uncertainty, otherwise it will not be rounded. The
	 * string is still rounded if {@code showUncertainty} is false.<br>
	 * UNCERTAINTY represents a string representation of this
	 * {@code UncertainDouble}'s uncertainty. If the uncertainty ends in 1X
	 * (where X represents any digit) it will be rounded to two significant
	 * digits otherwise it will be rounded to one significant digit.
	 * <p>
	 * Examples:
	 *
	 * <pre>
	 * UncertainDouble.of(3.27, 0.22).toString(false) = "3.3"
	 * UncertainDouble.of(3.27, 0.22).toString(true) = "3.3 ± 0.2"
	 * UncertainDouble.of(3.27, 0.13).toString(false) = "3.27"
	 * UncertainDouble.of(3.27, 0.13).toString(true) = "3.27 ± 0.13"
	 * UncertainDouble.of(-5.01, 0).toString(false) = "-5.01"
	 * UncertainDouble.of(-5.01, 0).toString(true) = "-5.01 ± 0.0"
	 * </pre>
	 *
	 * @param showUncertainty uncertainty is only shown if this parameter is true
	 * @param roundingMode    how to round values
	 * @return string representation of this {@code UncertainDouble}
	 *
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public String toString(boolean showUncertainty, RoundingMode roundingMode) {
		String valueString, uncertaintyString;

		// generate the string representation of value and uncertainty
		if (this.isExact()) {
			uncertaintyString = "0.0";
			valueString = Double.toString(this.value);

		} else {
			// round the value and uncertainty according to getDisplayScale()
			final var bigValue = BigDecimal.valueOf(this.value);
			final var bigUncertainty = BigDecimal.valueOf(this.uncertainty);

			final var displayScale = this.getDisplayScale();
			final var roundedUncertainty = bigUncertainty
					.setScale(displayScale, roundingMode);
			final var roundedValue = bigValue.setScale(displayScale,
					roundingMode);

			valueString = roundedValue.toString();
			uncertaintyString = roundedUncertainty.toString();
		}

		// return "value" or "value ± uncertainty" depending on showUncertainty
		return valueString + (showUncertainty ? " ± " + uncertaintyString : "");
	}

	/**
	 * @return absolute uncertainty
	 * @since 2020-09-07
	 * @since v0.3.0
	 */
	public double uncertainty() {
		return this.uncertainty;
	}

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