Debian Codegraph @

lib/3rdParty/composer/brick/math/src/BigDecimal.php

raw symbols SCIP
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Brick\Math;
6
7 use Brick\Math\Exception\DivisionByZeroException;
8 use Brick\Math\Exception\MathException;
9 use Brick\Math\Exception\NegativeNumberException;
10 use Brick\Math\Internal\Calculator;
11 use Override;
12
13 /**
14 * Immutable, arbitrary-precision signed decimal numbers.
15 *
16 * @psalm-immutable
17 */
18 final class BigDecimal extends BigNumber
19 {
20 /**
21 * The unscaled value of this decimal number.
22 *
23 * This is a string of digits with an optional leading minus sign.
24 * No leading zero must be present.
25 * No leading minus sign must be present if the value is 0.
26 */
27 private readonly string $value;
28
29 /**
30 * The scale (number of digits after the decimal point) of this decimal number.
31 *
32 * This must be zero or more.
33 */
34 private readonly int $scale;
35
36 /**
37 * Protected constructor. Use a factory method to obtain an instance.
38 *
39 * @param string $value The unscaled value, validated.
40 * @param int $scale The scale, validated.
41 */
42 protected function __construct(string $value, int $scale = 0)
43 {
44 $this->value = $value;
45 $this->scale = $scale;
46 }
47
48 /**
49 * @psalm-pure
50 */
51 #[Override]
52 protected static function from(BigNumber $number): static
53 {
54 return $number->toBigDecimal();
55 }
56
57 /**
58 * Creates a BigDecimal from an unscaled value and a scale.
59 *
60 * Example: `(12345, 3)` will result in the BigDecimal `12.345`.
61 *
62 * @param BigNumber|int|float|string $value The unscaled value. Must be convertible to a BigInteger.
63 * @param int $scale The scale of the number, positive or zero.
64 *
65 * @throws \InvalidArgumentException If the scale is negative.
66 *
67 * @psalm-pure
68 */
69 public static function ofUnscaledValue(BigNumber|int|float|string $value, int $scale = 0) : BigDecimal
70 {
71 if ($scale < 0) {
72 throw new \InvalidArgumentException('The scale cannot be negative.');
73 }
74
75 return new BigDecimal((string) BigInteger::of($value), $scale);
76 }
77
78 /**
79 * Returns a BigDecimal representing zero, with a scale of zero.
80 *
81 * @psalm-pure
82 */
83 public static function zero() : BigDecimal
84 {
85 /**
86 * @psalm-suppress ImpureStaticVariable
87 * @var BigDecimal|null $zero
88 */
89 static $zero;
90
91 if ($zero === null) {
92 $zero = new BigDecimal('0');
93 }
94
95 return $zero;
96 }
97
98 /**
99 * Returns a BigDecimal representing one, with a scale of zero.
100 *
101 * @psalm-pure
102 */
103 public static function one() : BigDecimal
104 {
105 /**
106 * @psalm-suppress ImpureStaticVariable
107 * @var BigDecimal|null $one
108 */
109 static $one;
110
111 if ($one === null) {
112 $one = new BigDecimal('1');
113 }
114
115 return $one;
116 }
117
118 /**
119 * Returns a BigDecimal representing ten, with a scale of zero.
120 *
121 * @psalm-pure
122 */
123 public static function ten() : BigDecimal
124 {
125 /**
126 * @psalm-suppress ImpureStaticVariable
127 * @var BigDecimal|null $ten
128 */
129 static $ten;
130
131 if ($ten === null) {
132 $ten = new BigDecimal('10');
133 }
134
135 return $ten;
136 }
137
138 /**
139 * Returns the sum of this number and the given one.
140 *
141 * The result has a scale of `max($this->scale, $that->scale)`.
142 *
143 * @param BigNumber|int|float|string $that The number to add. Must be convertible to a BigDecimal.
144 *
145 * @throws MathException If the number is not valid, or is not convertible to a BigDecimal.
146 */
147 public function plus(BigNumber|int|float|string $that) : BigDecimal
148 {
149 $that = BigDecimal::of($that);
150
151 if ($that->value === '0' && $that->scale <= $this->scale) {
152 return $this;
153 }
154
155 if ($this->value === '0' && $this->scale <= $that->scale) {
156 return $that;
157 }
158
159 [$a, $b] = $this->scaleValues($this, $that);
160
161 $value = Calculator::get()->add($a, $b);
162 $scale = $this->scale > $that->scale ? $this->scale : $that->scale;
163
164 return new BigDecimal($value, $scale);
165 }
166
167 /**
168 * Returns the difference of this number and the given one.
169 *
170 * The result has a scale of `max($this->scale, $that->scale)`.
171 *
172 * @param BigNumber|int|float|string $that The number to subtract. Must be convertible to a BigDecimal.
173 *
174 * @throws MathException If the number is not valid, or is not convertible to a BigDecimal.
175 */
176 public function minus(BigNumber|int|float|string $that) : BigDecimal
177 {
178 $that = BigDecimal::of($that);
179
180 if ($that->value === '0' && $that->scale <= $this->scale) {
181 return $this;
182 }
183
184 [$a, $b] = $this->scaleValues($this, $that);
185
186 $value = Calculator::get()->sub($a, $b);
187 $scale = $this->scale > $that->scale ? $this->scale : $that->scale;
188
189 return new BigDecimal($value, $scale);
190 }
191
192 /**
193 * Returns the product of this number and the given one.
194 *
195 * The result has a scale of `$this->scale + $that->scale`.
196 *
197 * @param BigNumber|int|float|string $that The multiplier. Must be convertible to a BigDecimal.
198 *
199 * @throws MathException If the multiplier is not a valid number, or is not convertible to a BigDecimal.
200 */
201 public function multipliedBy(BigNumber|int|float|string $that) : BigDecimal
202 {
203 $that = BigDecimal::of($that);
204
205 if ($that->value === '1' && $that->scale === 0) {
206 return $this;
207 }
208
209 if ($this->value === '1' && $this->scale === 0) {
210 return $that;
211 }
212
213 $value = Calculator::get()->mul($this->value, $that->value);
214 $scale = $this->scale + $that->scale;
215
216 return new BigDecimal($value, $scale);
217 }
218
219 /**
220 * Returns the result of the division of this number by the given one, at the given scale.
221 *
222 * @param BigNumber|int|float|string $that The divisor.
223 * @param int|null $scale The desired scale, or null to use the scale of this number.
224 * @param RoundingMode $roundingMode An optional rounding mode, defaults to UNNECESSARY.
225 *
226 * @throws \InvalidArgumentException If the scale or rounding mode is invalid.
227 * @throws MathException If the number is invalid, is zero, or rounding was necessary.
228 */
229 public function dividedBy(BigNumber|int|float|string $that, ?int $scale = null, RoundingMode $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal
230 {
231 $that = BigDecimal::of($that);
232
233 if ($that->isZero()) {
234 throw DivisionByZeroException::divisionByZero();
235 }
236
237 if ($scale === null) {
238 $scale = $this->scale;
239 } elseif ($scale < 0) {
240 throw new \InvalidArgumentException('Scale cannot be negative.');
241 }
242
243 if ($that->value === '1' && $that->scale === 0 && $scale === $this->scale) {
244 return $this;
245 }
246
247 $p = $this->valueWithMinScale($that->scale + $scale);
248 $q = $that->valueWithMinScale($this->scale - $scale);
249
250 $result = Calculator::get()->divRound($p, $q, $roundingMode);
251
252 return new BigDecimal($result, $scale);
253 }
254
255 /**
256 * Returns the exact result of the division of this number by the given one.
257 *
258 * The scale of the result is automatically calculated to fit all the fraction digits.
259 *
260 * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigDecimal.
261 *
262 * @throws MathException If the divisor is not a valid number, is not convertible to a BigDecimal, is zero,
263 * or the result yields an infinite number of digits.
264 */
265 public function exactlyDividedBy(BigNumber|int|float|string $that) : BigDecimal
266 {
267 $that = BigDecimal::of($that);
268
269 if ($that->value === '0') {
270 throw DivisionByZeroException::divisionByZero();
271 }
272
273 [, $b] = $this->scaleValues($this, $that);
274
275 $d = \rtrim($b, '0');
276 $scale = \strlen($b) - \strlen($d);
277
278 $calculator = Calculator::get();
279
280 foreach ([5, 2] as $prime) {
281 for (;;) {
282 $lastDigit = (int) $d[-1];
283
284 if ($lastDigit % $prime !== 0) {
285 break;
286 }
287
288 $d = $calculator->divQ($d, (string) $prime);
289 $scale++;
290 }
291 }
292
293 return $this->dividedBy($that, $scale)->stripTrailingZeros();
294 }
295
296 /**
297 * Returns this number exponentiated to the given value.
298 *
299 * The result has a scale of `$this->scale * $exponent`.
300 *
301 * @throws \InvalidArgumentException If the exponent is not in the range 0 to 1,000,000.
302 */
303 public function power(int $exponent) : BigDecimal
304 {
305 if ($exponent === 0) {
306 return BigDecimal::one();
307 }
308
309 if ($exponent === 1) {
310 return $this;
311 }
312
313 if ($exponent < 0 || $exponent > Calculator::MAX_POWER) {
314 throw new \InvalidArgumentException(\sprintf(
315 'The exponent %d is not in the range 0 to %d.',
316 $exponent,
317 Calculator::MAX_POWER
318 ));
319 }
320
321 return new BigDecimal(Calculator::get()->pow($this->value, $exponent), $this->scale * $exponent);
322 }
323
324 /**
325 * Returns the quotient of the division of this number by the given one.
326 *
327 * The quotient has a scale of `0`.
328 *
329 * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigDecimal.
330 *
331 * @throws MathException If the divisor is not a valid decimal number, or is zero.
332 */
333 public function quotient(BigNumber|int|float|string $that) : BigDecimal
334 {
335 $that = BigDecimal::of($that);
336
337 if ($that->isZero()) {
338 throw DivisionByZeroException::divisionByZero();
339 }
340
341 $p = $this->valueWithMinScale($that->scale);
342 $q = $that->valueWithMinScale($this->scale);
343
344 $quotient = Calculator::get()->divQ($p, $q);
345
346 return new BigDecimal($quotient, 0);
347 }
348
349 /**
350 * Returns the remainder of the division of this number by the given one.
351 *
352 * The remainder has a scale of `max($this->scale, $that->scale)`.
353 *
354 * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigDecimal.
355 *
356 * @throws MathException If the divisor is not a valid decimal number, or is zero.
357 */
358 public function remainder(BigNumber|int|float|string $that) : BigDecimal
359 {
360 $that = BigDecimal::of($that);
361
362 if ($that->isZero()) {
363 throw DivisionByZeroException::divisionByZero();
364 }
365
366 $p = $this->valueWithMinScale($that->scale);
367 $q = $that->valueWithMinScale($this->scale);
368
369 $remainder = Calculator::get()->divR($p, $q);
370
371 $scale = $this->scale > $that->scale ? $this->scale : $that->scale;
372
373 return new BigDecimal($remainder, $scale);
374 }
375
376 /**
377 * Returns the quotient and remainder of the division of this number by the given one.
378 *
379 * The quotient has a scale of `0`, and the remainder has a scale of `max($this->scale, $that->scale)`.
380 *
381 * @param BigNumber|int|float|string $that The divisor. Must be convertible to a BigDecimal.
382 *
383 * @return BigDecimal[] An array containing the quotient and the remainder.
384 *
385 * @psalm-return array{BigDecimal, BigDecimal}
386 *
387 * @throws MathException If the divisor is not a valid decimal number, or is zero.
388 */
389 public function quotientAndRemainder(BigNumber|int|float|string $that) : array
390 {
391 $that = BigDecimal::of($that);
392
393 if ($that->isZero()) {
394 throw DivisionByZeroException::divisionByZero();
395 }
396
397 $p = $this->valueWithMinScale($that->scale);
398 $q = $that->valueWithMinScale($this->scale);
399
400 [$quotient, $remainder] = Calculator::get()->divQR($p, $q);
401
402 $scale = $this->scale > $that->scale ? $this->scale : $that->scale;
403
404 $quotient = new BigDecimal($quotient, 0);
405 $remainder = new BigDecimal($remainder, $scale);
406
407 return [$quotient, $remainder];
408 }
409
410 /**
411 * Returns the square root of this number, rounded down to the given number of decimals.
412 *
413 * @throws \InvalidArgumentException If the scale is negative.
414 * @throws NegativeNumberException If this number is negative.
415 */
416 public function sqrt(int $scale) : BigDecimal
417 {
418 if ($scale < 0) {
419 throw new \InvalidArgumentException('Scale cannot be negative.');
420 }
421
422 if ($this->value === '0') {
423 return new BigDecimal('0', $scale);
424 }
425
426 if ($this->value[0] === '-') {
427 throw new NegativeNumberException('Cannot calculate the square root of a negative number.');
428 }
429
430 $value = $this->value;
431 $addDigits = 2 * $scale - $this->scale;
432
433 if ($addDigits > 0) {
434 // add zeros
435 $value .= \str_repeat('0', $addDigits);
436 } elseif ($addDigits < 0) {
437 // trim digits
438 if (-$addDigits >= \strlen($this->value)) {
439 // requesting a scale too low, will always yield a zero result
440 return new BigDecimal('0', $scale);
441 }
442
443 $value = \substr($value, 0, $addDigits);
444 }
445
446 $value = Calculator::get()->sqrt($value);
447
448 return new BigDecimal($value, $scale);
449 }
450
451 /**
452 * Returns a copy of this BigDecimal with the decimal point moved $n places to the left.
453 */
454 public function withPointMovedLeft(int $n) : BigDecimal
455 {
456 if ($n === 0) {
457 return $this;
458 }
459
460 if ($n < 0) {
461 return $this->withPointMovedRight(-$n);
462 }
463
464 return new BigDecimal($this->value, $this->scale + $n);
465 }
466
467 /**
468 * Returns a copy of this BigDecimal with the decimal point moved $n places to the right.
469 */
470 public function withPointMovedRight(int $n) : BigDecimal
471 {
472 if ($n === 0) {
473 return $this;
474 }
475
476 if ($n < 0) {
477 return $this->withPointMovedLeft(-$n);
478 }
479
480 $value = $this->value;
481 $scale = $this->scale - $n;
482
483 if ($scale < 0) {
484 if ($value !== '0') {
485 $value .= \str_repeat('0', -$scale);
486 }
487 $scale = 0;
488 }
489
490 return new BigDecimal($value, $scale);
491 }
492
493 /**
494 * Returns a copy of this BigDecimal with any trailing zeros removed from the fractional part.
495 */
496 public function stripTrailingZeros() : BigDecimal
497 {
498 if ($this->scale === 0) {
499 return $this;
500 }
501
502 $trimmedValue = \rtrim($this->value, '0');
503
504 if ($trimmedValue === '') {
505 return BigDecimal::zero();
506 }
507
508 $trimmableZeros = \strlen($this->value) - \strlen($trimmedValue);
509
510 if ($trimmableZeros === 0) {
511 return $this;
512 }
513
514 if ($trimmableZeros > $this->scale) {
515 $trimmableZeros = $this->scale;
516 }
517
518 $value = \substr($this->value, 0, -$trimmableZeros);
519 $scale = $this->scale - $trimmableZeros;
520
521 return new BigDecimal($value, $scale);
522 }
523
524 /**
525 * Returns the absolute value of this number.
526 */
527 public function abs() : BigDecimal
528 {
529 return $this->isNegative() ? $this->negated() : $this;
530 }
531
532 /**
533 * Returns the negated value of this number.
534 */
535 public function negated() : BigDecimal
536 {
537 return new BigDecimal(Calculator::get()->neg($this->value), $this->scale);
538 }
539
540 #[Override]
541 public function compareTo(BigNumber|int|float|string $that) : int
542 {
543 $that = BigNumber::of($that);
544
545 if ($that instanceof BigInteger) {
546 $that = $that->toBigDecimal();
547 }
548
549 if ($that instanceof BigDecimal) {
550 [$a, $b] = $this->scaleValues($this, $that);
551
552 return Calculator::get()->cmp($a, $b);
553 }
554
555 return - $that->compareTo($this);
556 }
557
558 #[Override]
559 public function getSign() : int
560 {
561 return ($this->value === '0') ? 0 : (($this->value[0] === '-') ? -1 : 1);
562 }
563
564 public function getUnscaledValue() : BigInteger
565 {
566 return self::newBigInteger($this->value);
567 }
568
569 public function getScale() : int
570 {
571 return $this->scale;
572 }
573
574 /**
575 * Returns the number of significant digits in the number.
576 *
577 * This is the number of digits to both sides of the decimal point, stripped of leading zeros.
578 * The sign has no impact on the result.
579 *
580 * Examples:
581 * 0 => 0
582 * 0.0 => 0
583 * 123 => 3
584 * 123.456 => 6
585 * 0.00123 => 3
586 * 0.0012300 => 5
587 */
588 public function getPrecision(): int
589 {
590 $value = $this->value;
591
592 if ($value === '0') {
593 return 0;
594 }
595
596 $length = \strlen($value);
597
598 return ($value[0] === '-') ? $length - 1 : $length;
599 }
600
601 /**
602 * Returns a string representing the integral part of this decimal number.
603 *
604 * Example: `-123.456` => `-123`.
605 */
606 public function getIntegralPart() : string
607 {
608 if ($this->scale === 0) {
609 return $this->value;
610 }
611
612 $value = $this->getUnscaledValueWithLeadingZeros();
613
614 return \substr($value, 0, -$this->scale);
615 }
616
617 /**
618 * Returns a string representing the fractional part of this decimal number.
619 *
620 * If the scale is zero, an empty string is returned.
621 *
622 * Examples: `-123.456` => '456', `123` => ''.
623 */
624 public function getFractionalPart() : string
625 {
626 if ($this->scale === 0) {
627 return '';
628 }
629
630 $value = $this->getUnscaledValueWithLeadingZeros();
631
632 return \substr($value, -$this->scale);
633 }
634
635 /**
636 * Returns whether this decimal number has a non-zero fractional part.
637 */
638 public function hasNonZeroFractionalPart() : bool
639 {
640 return $this->getFractionalPart() !== \str_repeat('0', $this->scale);
641 }
642
643 #[Override]
644 public function toBigInteger() : BigInteger
645 {
646 $zeroScaleDecimal = $this->scale === 0 ? $this : $this->dividedBy(1, 0);
647
648 return self::newBigInteger($zeroScaleDecimal->value);
649 }
650
651 #[Override]
652 public function toBigDecimal() : BigDecimal
653 {
654 return $this;
655 }
656
657 #[Override]
658 public function toBigRational() : BigRational
659 {
660 $numerator = self::newBigInteger($this->value);
661 $denominator = self::newBigInteger('1' . \str_repeat('0', $this->scale));
662
663 return self::newBigRational($numerator, $denominator, false);
664 }
665
666 #[Override]
667 public function toScale(int $scale, RoundingMode $roundingMode = RoundingMode::UNNECESSARY) : BigDecimal
668 {
669 if ($scale === $this->scale) {
670 return $this;
671 }
672
673 return $this->dividedBy(BigDecimal::one(), $scale, $roundingMode);
674 }
675
676 #[Override]
677 public function toInt() : int
678 {
679 return $this->toBigInteger()->toInt();
680 }
681
682 #[Override]
683 public function toFloat() : float
684 {
685 return (float) (string) $this;
686 }
687
688 #[Override]
689 public function __toString() : string
690 {
691 if ($this->scale === 0) {
692 return $this->value;
693 }
694
695 $value = $this->getUnscaledValueWithLeadingZeros();
696
697 return \substr($value, 0, -$this->scale) . '.' . \substr($value, -$this->scale);
698 }
699
700 /**
701 * This method is required for serializing the object and SHOULD NOT be accessed directly.
702 *
703 * @internal
704 *
705 * @return array{value: string, scale: int}
706 */
707 public function __serialize(): array
708 {
709 return ['value' => $this->value, 'scale' => $this->scale];
710 }
711
712 /**
713 * This method is only here to allow unserializing the object and cannot be accessed directly.
714 *
715 * @internal
716 * @psalm-suppress RedundantPropertyInitializationCheck
717 *
718 * @param array{value: string, scale: int} $data
719 *
720 * @throws \LogicException
721 */
722 public function __unserialize(array $data): void
723 {
724 if (isset($this->value)) {
725 throw new \LogicException('__unserialize() is an internal function, it must not be called directly.');
726 }
727
728 $this->value = $data['value'];
729 $this->scale = $data['scale'];
730 }
731
732 /**
733 * Puts the internal values of the given decimal numbers on the same scale.
734 *
735 * @return array{string, string} The scaled integer values of $x and $y.
736 */
737 private function scaleValues(BigDecimal $x, BigDecimal $y) : array
738 {
739 $a = $x->value;
740 $b = $y->value;
741
742 if ($b !== '0' && $x->scale > $y->scale) {
743 $b .= \str_repeat('0', $x->scale - $y->scale);
744 } elseif ($a !== '0' && $x->scale < $y->scale) {
745 $a .= \str_repeat('0', $y->scale - $x->scale);
746 }
747
748 return [$a, $b];
749 }
750
751 private function valueWithMinScale(int $scale) : string
752 {
753 $value = $this->value;
754
755 if ($this->value !== '0' && $scale > $this->scale) {
756 $value .= \str_repeat('0', $scale - $this->scale);
757 }
758
759 return $value;
760 }
761
762 /**
763 * Adds leading zeros if necessary to the unscaled value to represent the full decimal number.
764 */
765 private function getUnscaledValueWithLeadingZeros() : string
766 {
767 $value = $this->value;
768 $targetLength = $this->scale + 1;
769 $negative = ($value[0] === '-');
770 $length = \strlen($value);
771
772 if ($negative) {
773 $length--;
774 }
775
776 if ($length >= $targetLength) {
777 return $this->value;
778 }
779
780 if ($negative) {
781 $value = \substr($value, 1);
782 }
783
784 $value = \str_pad($value, $targetLength, '0', STR_PAD_LEFT);
785
786 if ($negative) {
787 $value = '-' . $value;
788 }
789
790 return $value;
791 }
792 }