-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBigNumber.php
854 lines (745 loc) · 16.6 KB
/
BigNumber.php
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
<?php
namespace Aza\Components\Math;
use Aza\Components\Math\Exceptions\Exception;
/**
* Functionality to
* Represents a number for arbitrary precision
* arithmetic computations.
*
* Based on {@link https://github.com/moontoast/math Moontoast Math Library}
*
* @package system.math
* @author Amal Samally <amal.samally at gmail.com>
* @license MIT
*/
class BigNumber
{
// Round modes
const ROUND_HALF_UP = PHP_ROUND_HALF_UP; // 1
const ROUND_HALF_DOWN = PHP_ROUND_HALF_DOWN; // 2
/**
* Simple cut at the specified digit after dot.
* Value choosed to not conflict with PHP_ROUND_* constants.
*/
const ROUND_CUT = 8;
/**
* Flag if BCmath extension is available
*/
public static $hasBcmath = false;
/**
* Default precision
* (number of digits after the decimal place)
*/
protected static $defaultScale = -1;
/**
* Number value, as a string
*
* @var string
*/
protected $value;
/**
* The scale for the current number
*
* @var int
*/
protected $scale;
/**
* Constructs an object from a string, integer, float,
* or any object that may be cast to a string, resulting
* in a numeric string value
*
* @param mixed $number <p>
* May be of any type that can be cast to a string
* representation of a base 10 number.
* </p>
* @param int $scale [optional] <p>
* Specifies the default number of digits after the decimal
* place to be used in operations for this number
* </p>
*
* @throws Exception
*/
public function __construct($number = 0, $scale = null)
{
if (!self::$hasBcmath) {
throw new Exception(
"You need BCMath extension enabled to work with BigNumber"
);
}
isset($scale)
? $this->setCalcScale($scale)
: $this->scale = self::$defaultScale;
$this->setValue($number);
}
/**
* Returns the string value of this number
*
* @return string String representation of the number
*/
public function __toString()
{
return $this->getValue();
}
/**
* Returns the current number scale
*
* @return int
*/
public function getScale()
{
$value = $this->trim($this->value);
return false !== ($pos = strpos($value, '.'))
? strlen($value) - $pos - 1
: -1;
}
/**
* Returns the calculation scale used for this number
*
* @return int
*/
public function getCalcScale()
{
return $this->scale;
}
/**
* Returns the current value of this number (trimmed)
*
* @return string String representation of the number in base 10
*/
public function getValue()
{
return $this->trim($this->value);
}
/**
* Sets the calculation scale of this number
*
* @param int $scale Specifies the default number of digits after the decimal
* place to be used in operations for this number
*
* @return self for chainning
*/
public function setCalcScale($scale)
{
$this->scale = $scale > 0 ? (int)$scale : 0;
return $this;
}
/**
* Sets the value of this number to a new value
*
* @param mixed $number <p>
* May be of any type that can be cast to a string
* representation of a base 10 number.
* </p>
*
* @return self for chainning
*/
public function setValue($number)
{
// Check for invalid input, empty string (false, null)
('' === (string)$number)
&& $number = '0';
// Set the scale for the number to the scale value passed in
// bcsub is fastest variant
$number = bcsub(
$this->filterNumber($number),
'0',
$this->scale
);
$this->value = $number;
return $this;
}
/**
* Sets the current number to the absolute value of itself
*
* @return self for chainning
*/
public function abs()
{
// Negative numbers starts with '-' character
'-' === $this->value[0]
&& $this->value = substr($this->value, 1);
return $this;
}
/**
* Adds the given number to the current number
*
* @param mixed $number <p>
* May be of any type that can be cast to a string
* representation of a base 10 number
*
* @return self for chainning
* @see bcadd
*/
public function add($number)
{
$this->value = bcadd(
$this->value,
$this->filterNumber($number),
$this->scale
);
return $this;
}
/**
* Subtracts the given number from the current number
*
* @see bcsub
*
* @param mixed $number <p>
* May be of any type that can be cast to a string
* representation of a base 10 number.
* </p>
*
* @return self for chainning
*/
public function subtract($number)
{
$this->value = bcsub(
$this->value,
$this->filterNumber($number),
$this->scale
);
return $this;
}
/**
* Multiplies the current number by the given number
*
* @see bcmul
*
* @param mixed $number <p>
* May be of any type that can be cast to a string
* representation of a base 10 number.
* </p>
*
* @return self for chainning
*/
public function multiply($number)
{
$this->value = bcmul(
$this->value,
$this->filterNumber($number),
$this->scale
);
return $this;
}
/**
* Divides the current number by the given number
*
* @see bcdiv
*
* @param mixed $number <p>
* May be of any type that can be cast to a string
* representation of a base 10 number.
* </p>
*
* @return self for chainning
* @throws Exception if $number is zero
*/
public function divide($number)
{
$number = $this->filterNumber($number);
if ('0' == $number) {
throw new Exception('Division by zero');
}
$this->value = bcdiv(
$this->value,
$number,
$this->scale
);
return $this;
}
/**
* Finds the modulus (remainder) of the current number
* divided by the given number
*
* @TODO: Support fraction argument for mod()
*
* @param mixed $number <p>
* May be of any type that can be cast to a string
* representation of a base 10 number.
* </p>
*
* @return self for chainning
* @throws Exception if $number is zero
* @see bcmod
*/
public function mod($number)
{
$number = $this->filterNumber($number);
if ('0' === $number) {
throw new Exception('Division by zero');
}
$this->value = bcmod(
$this->value,
$number
);
return $this;
}
/**
* Raises current number to the given number
*
* @TODO: Support fraction argument for pow()
*
* @param mixed $number <p>
* May be of any type that can be cast to a string
* representation of a base 10 number.
* </p>
*
* @return self for chainning
* @see bcpow
*/
public function pow($number)
{
$this->value = bcpow(
$this->value,
$this->filterNumber($number),
$this->scale
);
return $this;
}
/**
* Raises the current number to the $pow, then divides by the $mod
* to find the modulus
*
* This is functionally equivalent code:
*
* <code>
* (new BigNumber(10))->powMod(20, 30);
* (new BigNumber(10))->pow(20)->mod(30);
* </code>
*
* However powMod() uses bcpowmod(), so it is faster
* and can accept larger parameters.
*
* @TODO: Support fraction arguments for powMod()
*
* @see bcpowmod
*
* @param mixed $pow May be of any type that can be cast to a string
* representation of a base 10 number
* @param mixed $mod May be of any type that can be cast to a string
* representation of a base 10 number
*
* @return self for chainning
*
* @throws Exception if $number is zero
*/
public function powMod($pow, $mod)
{
$mod = $this->filterNumber($mod);
if ('0' === $mod) {
throw new Exception('Division by zero');
}
// when there's a dot in one of bcpowmod's parameters (it's a float),
// you'll get a "bc math warning: non-zerio scale in <whatever>"
// so we need to use trim even for integer value (it will be 12.0000...)
$val = $this->trim($this->value);
$pow = $this->filterNumber($pow);
$this->value = bcpowmod(
$val, $pow, $mod
);
return $this;
}
/**
* Finds the square root of the current number
*
* @TODO: Nth root calculation method
*
* @return self for chainning
* @see bcsqrt
*/
public function sqrt()
{
$this->value = bcsqrt(
$this->value,
$this->scale
);
return $this;
}
/**
* Shifts the current number $bits to the left
*
* @param int $bits
*
* @return self for chainning
*/
public function shiftLeft($bits)
{
$this->value = bcmul(
$this->value,
bcpow('2', $bits)
);
return $this;
}
/**
* Shifts the current number $bits to the right
*
* @param int $bits
*
* @return self for chainning
*/
public function shiftRight($bits)
{
$this->value = bcdiv(
$this->value,
bcpow('2', $bits)
);
return $this;
}
/**
* Returns the rounded value of val to specified precision
* (number of digits after the decimal point).
*
* @param int $precision [optional] <p>
* The optional number of decimal digits to round to.
* </p>
* @param int $mode [optional] <p>
* One of BigNumber::ROUND_HALF_UP (equivalent of PHP_ROUND_HALF_UP),
* BigNumber::ROUND_HALF_DOWN (equivalent of PHP_ROUND_HALF_DOWN),
* BigNumber::ROUND_CUT
* </p>
*
* @return self for chainning
*/
public function round($precision = 0, $mode = self::ROUND_HALF_UP)
{
if ($precision >= $scale = $this->getScale()) {
// Value is already rounded
return $this;
}
// ROUND_CUT
if (self::ROUND_CUT == $mode) {
$value = bcadd($this->value, 0, $precision);
}
// HALF_UP / HALF_DOWN
else {
$original = $this->value;
$floored = $this->floor()->value;
$diff = bcsub($original, $floored, $scale);
$roundedDiff = round($diff, $precision, $mode);
$value = bcadd($floored, $roundedDiff, $precision);
}
$this->value = $value;
return $this;
}
/**
* Finds the next lowest integer value by rounding down
* the current number if necessary
*
* @see floor
*
* @return self for chainning
*/
public function floor()
{
$number = $this->value;
if ($this->isNegative()) {
// 14 is the magic precision number
$number = bcadd($number, '0', 14);
if ('.00000000000000' !== substr($number, -15)) {
$number = bcsub($number, '1', 0);
}
}
$this->value = bcadd($number, '0', 0);
return $this;
}
/**
* Finds the next highest integer value by rounding up
* the current number if necessary
*
* @see ceil
*
* @return self for chainning
*/
public function ceil()
{
$number = $this->value;
if ($this->isPositive()) {
// 14 is the magic precision number
$number = bcadd($number, '0', 14);
if ('.00000000000000' !== substr($number, -15)) {
$number = bcadd($number, '1', 0);
}
}
$this->value = bcadd($number, '0', 0);
return $this;
}
/**
* Increases the value of the current number by one
*
* @return self for chainning
*/
public function increment()
{
return $this->add(1);
}
/**
* Decreases the value of the current number by one
*
* @return self for chainning
*/
public function decrement()
{
return $this->subtract(1);
}
/**
* Compares the current number with the given number
*
* Returns 0 if the two operands are equal, 1 if the current number is
* larger than the given number, -1 otherwise.
*
* @param mixed $number <p>
* May be of any type that can be cast to a string
* representation of a base 10 number.
* </p>
*
* @return int
* @see bccomp
*/
public function compareTo($number)
{
return bccomp(
$this->value,
$this->filterNumber($number),
$this->scale
);
}
/**
* Returns true if the current number equals the given number
*
* @param mixed $number <p>
* May be of any type that can be cast to a string
* representation of a base 10 number.
* </p>
*
* @return bool
*/
public function isEqualTo($number)
{
return 0 == $this->compareTo($number);
}
/**
* Returns true if the current number is greater than the given number
*
* @param mixed $number <p>
* May be of any type that can be cast to a string
* representation of a base 10 number.
* </p>
*
* @return bool
*/
public function isGreaterThan($number)
{
return 1 == $this->compareTo($number);
}
/**
* Returns true if the current number is greater than or equal to the given number
*
* @param mixed $number <p>
* May be of any type that can be cast to a string
* representation of a base 10 number.
* </p>
*
* @return bool
*/
public function isGreaterThanOrEqualTo($number)
{
return $this->compareTo($number) >= 0;
}
/**
* Returns true if the current number is less
* than the given number
*
* @param mixed $number <p>
* May be of any type that can be cast to a string
* representation of a base 10 number.
* </p>
*
* @return bool
*/
public function isLessThan($number)
{
return -1 == $this->compareTo($number);
}
/**
* Returns true if the current number is less
* than or equal to the given number
*
* @param mixed $number <p>
* May be of any type that can be cast to a string
* representation of a base 10 number.
* </p>
*
* @return bool
*/
public function isLessThanOrEqualTo($number)
{
return $this->compareTo($number) <= 0;
}
/**
* Sign function. Returns the sign of the current number
*
* @return int -1, 0 or 1 as the value of this number is negative, zero or positive
*/
public function signum()
{
if ($this->isGreaterThan(0)) {
return 1;
} else if ($this->isLessThan(0)) {
return -1;
}
return 0;
}
/**
* Returns true if the current number is a negative number
*
* @return bool
*/
public function isNegative()
{
// Negative numbers starts with '-' character
return '-' === $this->value[0];
}
/**
* Returns true if the current number is a positive number
*
* @return bool
*/
public function isPositive()
{
// Negative numbers starts with '-' character
return '-' !== $this->value[0];
}
/**
* Sets the current number to the negative value of itself
*
* @return self for chainning
*/
public function negate()
{
// TODO: May be use substr + concatenation? Most likely it'll be faster
return $this->multiply(-1);
}
/**
* Returns the current value converted to an arbitrary base
*
* @see NumeralSystem::convert
*
* @param int|string $base <p>
* Target number system.
* </p>
*
* @return string String representation of the number in the given base
*/
public function convertToBase($base)
{
return NumeralSystem::convert(
$this->trim($this->value),
10, $base
);
}
/**
* Filters a number, converting it to a string value.
*
* Prepares a number without scientific (exponential)
* notation and without loosing precision
* (as far as possible).
*
* Without this, floats/doubles loses precision just awfully.
* See tests in {@link BigNumberBenchmarkTest::testPrepareFloat}.
*
* @param mixed $number
*
* @return string
*/
protected function filterNumber($number)
{
// 16 is the best value. was obtained empirically
(16 !== ($oldPrecision = ini_get('precision')))
&& ini_set('precision', 16);
$number = (string)$number;
(16 !== $oldPrecision)
&& ini_set('precision', $oldPrecision);
// Expand scientific (exponential) support
if (false !== ($pos = strpos($number, 'E'))
|| false !== ($pos = strpos($number, 'e'))
) {
$firstPart = filter_var(
substr($number, 0, $pos),
FILTER_SANITIZE_NUMBER_FLOAT,
FILTER_FLAG_ALLOW_FRACTION
);
if ('-' === $number[$pos+1]) {
$secondPart = filter_var(
substr($number, $pos+2),
FILTER_SANITIZE_NUMBER_FLOAT,
FILTER_FLAG_ALLOW_FRACTION
);
return bcdiv(
$firstPart,
bcpow('10', $secondPart, 0),
100
);
} else {
$secondPart = filter_var(
substr($number, $pos+1),
FILTER_SANITIZE_NUMBER_FLOAT,
FILTER_FLAG_ALLOW_FRACTION
);
return bcmul(
$firstPart,
bcpow('10', $secondPart, 0),
100
);
}
}
return filter_var(
$number,
FILTER_SANITIZE_NUMBER_FLOAT,
FILTER_FLAG_ALLOW_FRACTION
);
}
/**
* Trims trailing zeros of an arbitrary precision number.
*
* Uses fastest algorithm. See comparision in
* {@link BigNumberBenchmarkTest::testTrim}.
*
* @param string $number
*
* @return string
*/
protected function trim($number)
{
if (false === $pos = strpos($number, '.')) {
return $number;
}
return substr($number, 0, $pos) . rtrim(substr($number, $pos), '.0');
}
/**
* Changes the default scale
*
* @return int
*/
public static function getDefaultScale()
{
return self::$defaultScale;
}
/**
* Changes the default scale
*
* @param int $scale
*/
public static function setDefaultScale($scale)
{
self::$defaultScale = $scale > 0 ? (int)$scale : 0;
}
}
// @codeCoverageIgnoreStart
// Check if we have BCmath extension enabled
(BigNumber::$hasBcmath = extension_loaded('bcmath'))
// Check default scale
&& BigNumber::setDefaultScale(strlen(bcsub(0, 0))-2);
// Set default scale to 100 if not set
(BigNumber::getDefaultScale() < 100)
&& BigNumber::setDefaultScale(100);
// @codeCoverageIgnoreEnd