-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
numbers.py
2594 lines (2034 loc) · 72.2 KB
/
numbers.py
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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import decimal
import fractions
import math
import numbers
import mpmath
import mpmath.libmp as mlib
from .cache import cacheit
from .compatibility import GROUND_TYPES, HAS_GMPY, as_int, gmpy
from .containers import Tuple
from .decorators import _sympifyit
from .expr import AtomicExpr, Expr
from .logic import fuzzy_not
from .singleton import S, SingletonWithManagedProperties
from .sympify import SympifyError, converter, sympify
rnd = mlib.round_nearest
def comp(z1, z2, tol=None):
"""Return a bool indicating whether the error between z1 and z2 is <= tol.
If ``tol`` is None then True will be returned if there is a significant
difference between the numbers: ``abs(z1 - z2)*10**p <= 1/2`` where ``p``
is the lower of the precisions of the values. A comparison of strings will
be made if ``z1`` is a Number and a) ``z2`` is a string or b) ``tol`` is ''
and ``z2`` is a Number.
When ``tol`` is a nonzero value, if z2 is non-zero and ``|z1| > 1``
the error is normalized by ``|z1|``, so if you want to see if the
absolute error between ``z1`` and ``z2`` is <= ``tol`` then call this
as ``comp(z1 - z2, 0, tol)``.
"""
if type(z2) is str:
if not isinstance(z1, Number):
raise ValueError('when z2 is a str z1 must be a Number')
return str(z1) == z2
if not z1:
z1, z2 = z2, z1
if not z1:
return True
if not tol:
if tol is None:
a, b = Float(z1), Float(z2)
return int(abs(a - b)*10**mlib.prec_to_dps(
min(a._prec, b._prec)))*2 <= 1
elif all(getattr(i, 'is_Number', False) for i in (z1, z2)):
return z1._prec == z2._prec and str(z1) == str(z2)
raise ValueError('exact comparison requires two Numbers')
diff = abs(z1 - z2)
az1 = abs(z1)
if z2 and az1 > 1:
return diff/az1 <= tol
else:
return diff <= tol
def mpf_norm(mpf, prec):
"""Return the mpf tuple normalized appropriately for the indicated
precision after doing a check to see if zero should be returned or
not when the mantissa is 0. ``mlib.normalize`` always assumes that this
is zero, but it may not be since the mantissa for mpf's values "+inf",
"-inf" and "nan" have a mantissa of zero, too.
Note: this is not intended to validate a given mpf tuple, so sending
mpf tuples that were not created by mpmath may produce bad results. This
is only a wrapper to ``mpmath.libmp.normalize`` which provides the check
for non-zero mpfs that have a 0 for the mantissa.
"""
sign, man, expt, bc = mpf
if not man:
# hack for normalize which does not do this;
# it assumes that if man is zero the result is 0
# (see issue sympy/sympy#6639)
if not bc:
return mlib.fzero
else:
# don't change anything; this should already
# be a well formed mpf tuple
return mpf
rv = mlib.normalize(sign, man, expt, bc, prec, rnd)
return rv
def _str_to_Decimal_dps(s):
"""Convert a string to pair of a Decimal instance and its precision."""
try:
num = decimal.Decimal(s)
except decimal.InvalidOperation:
raise ValueError(f'string-float not recognized: {s}')
else:
return num, len(num.as_tuple().digits)
@cacheit
def igcd(*args):
"""Computes positive integer greatest common divisor.
Examples
========
>>> igcd(2, 4)
2
>>> igcd(5, 10, 15)
5
"""
args = map(as_int, args)
a = next(args)
for b in args:
if a == 1:
break
a = math.gcd(a, b)
return a
def ilcm(*args):
"""Computes integer least common multiple.
Examples
========
>>> ilcm(5, 10)
10
>>> ilcm(7, 3)
21
>>> ilcm(5, 10, 15)
30
"""
args = map(as_int, args)
a = next(args)
for b in args:
if a == 0:
break
a = a*b // math.gcd(a, b)
return a
def igcdex(a, b):
"""Returns x, y, g such that g = x*a + y*b = gcd(a, b).
>>> igcdex(2, 3)
(-1, 1, 1)
>>> igcdex(10, 12)
(-1, 1, 2)
>>> igcdex(100, 2004)
(-20, 1, 4)
>>> x, y = _[:-1]
>>> x*100 + y*2004
4
"""
if (not a) and (not b):
return 0, 1, 0
if not a:
return 0, b//abs(b), abs(b)
if not b:
return a//abs(a), 0, abs(a)
if a < 0:
a, x_sign = -a, -1
else:
x_sign = 1
if b < 0:
b, y_sign = -b, -1
else:
y_sign = 1
x, y, r, s = 1, 0, 0, 1
while b:
c, q = a % b, a // b
a, b, r, s, x, y = b, c, x - q*r, y - q*s, r, s
return x*x_sign, y*y_sign, a
def mod_inverse(a, m):
"""
Return the number c such that, ( a * c ) % m == 1 where
c has the same sign as a. If no such value exists, a
ValueError is raised.
Examples
========
Suppose we wish to find multiplicative inverse x of
3 modulo 11. This is the same as finding x such
that 3 * x = 1 (mod 11). One value of x that satisfies
this congruence is 4. Because 3 * 4 = 12 and 12 = 1 mod(11).
This is the value return by mod_inverse:
>>> mod_inverse(3, 11)
4
>>> mod_inverse(-3, 11)
-4
When there is a common factor between the numerators of
``a`` and ``m`` the inverse does not exist:
>>> mod_inverse(2, 4)
Traceback (most recent call last):
...
ValueError: inverse of 2 mod 4 does not exist
>>> mod_inverse(Integer(2)/7, Integer(5)/2)
7/2
References
==========
* https://en.wikipedia.org/wiki/Modular_multiplicative_inverse
* https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
"""
from ..utilities import filldedent
c = None
try:
a, m = as_int(a), as_int(m)
if m > 1:
x, y, g = igcdex(a, m)
if g == 1:
c = x % m
if a < 0:
c -= m
except ValueError:
a, m = sympify(a), sympify(m)
if not (a.is_number and m.is_number):
raise TypeError(filldedent("""
Expected numbers for arguments; symbolic `mod_inverse`
is not implemented
but symbolic expressions can be handled with the
similar function,
sympy.polys.polytools.invert"""))
big = (m > 1)
if not (big is S.true or big is S.false):
raise ValueError(f'm > 1 did not evaluate; try to simplify {m}')
elif big:
c = 1/a
if c is None:
raise ValueError(f'inverse of {a} (mod {m}) does not exist')
return c
def integer_digits(n, b):
"""Gives a list of the base `b` digits in the integer `n`."""
n, b = map(as_int, (n, b))
if n == 0:
return [0]
digits = []
while n:
digits.append(n % b)
n //= b
return digits[::-1]
class Number(AtomicExpr):
"""
Represents any kind of number in diofant.
Floating point numbers are represented by the Float class.
Integer numbers (of any size), together with rational numbers (again,
there is no limit on their size) are represented by the Rational class.
"""
is_commutative = True
is_number = True
is_Number = True
# Used to make max(x._prec, y._prec) return x._prec when only x is a float
_prec = -1
def __new__(cls, *obj):
if len(obj) == 1:
obj = obj[0]
if isinstance(obj, Number):
return obj
if isinstance(obj, numbers.Integral):
return Integer(obj)
if isinstance(obj, tuple) and len(obj) == 2:
return Rational(*obj)
if isinstance(obj, (float, mpmath.mpf, decimal.Decimal)):
return Float(obj)
if isinstance(obj, str):
val = sympify(obj)
if isinstance(val, Number):
return val
else:
raise ValueError(f'String "{obj}" does not denote a Number')
msg = 'expected str|int|float|Decimal|Number object but got %r'
raise TypeError(msg % type(obj).__name__)
def invert(self, other, *gens, **args):
from ..polys.polytools import invert
if getattr(other, 'is_number', True):
return mod_inverse(self, other)
return invert(self, other, *gens, **args)
@_sympifyit('other', NotImplemented)
def __divmod__(self, other):
if not other:
raise ZeroDivisionError('modulo by zero')
elif self.is_Integer and other.is_Integer:
return Tuple(*divmod(self.numerator, other.numerator))
else:
rat = self/other
w = math.floor(rat)
r = self - other*w
return Tuple(w, r)
@_sympifyit('other', NotImplemented)
def __rdivmod__(self, other):
return divmod(other, self)
def __round__(self, *args):
return round(float(self), *args)
def _as_mpf_val(self, prec): # pragma: no cover
"""Evaluation of mpf tuple accurate to at least prec bits."""
raise NotImplementedError(f'{self.__class__.__name__} needs ._as_mpf_val() method')
def _eval_evalf(self, prec):
return Float._new(self._as_mpf_val(prec), prec)
def _as_mpf_op(self, prec):
prec = max(prec, self._prec)
return self._as_mpf_val(prec), prec
def __float__(self):
return mlib.to_float(self._as_mpf_val(53))
def _eval_conjugate(self):
return self
def _eval_subs(self, old, new):
if old == -self:
return -new
return self # there is no other possibility
@classmethod
def class_key(cls):
"""Nice order of classes."""
return 1, 0, 'Number'
@cacheit
def sort_key(self, order=None):
"""Return a sort key."""
return self.class_key(), (0, ()), (), self
def __hash__(self):
return super().__hash__()
def is_constant(self, *wrt, **flags):
"""Return True if self is constant.
See Also
========
diofant.core.expr.Expr.is_constant
"""
return True
def as_coeff_mul(self, *deps, **kwargs):
"""Return the tuple (c, args) where self is written as a Mul.
See Also
========
diofant.core.expr.Expr.as_coeff_mul
"""
# a -> c*t
if self.is_Rational or not kwargs.pop('rational', True):
return self, ()
elif self.is_negative:
return S.NegativeOne, (-self,)
return S.One, (self,)
def as_coeff_add(self, *deps):
"""Return the tuple (c, args) where self is written as an Add.
See Also
========
diofant.core.expr.Expr.as_coeff_add
"""
# a -> c + t
if self.is_Rational:
return self, ()
return S.Zero, (self,)
def as_coeff_Mul(self, rational=False):
"""Efficiently extract the coefficient of a product."""
if rational and not self.is_Rational:
return S.One, self
return (self, S.One) if self else (S.One, self)
def as_coeff_Add(self, rational=False):
"""Efficiently extract the coefficient of a summation."""
if not rational:
return self, S.Zero
return S.Zero, self
def gcd(self, other):
"""Compute GCD of `self` and `other`."""
from ..polys import gcd
return gcd(self, other)
def lcm(self, other):
"""Compute LCM of `self` and `other`."""
from ..polys import lcm
return lcm(self, other)
def cofactors(self, other):
"""Compute GCD and cofactors of `self` and `other`."""
from ..polys import cofactors
return cofactors(self, other)
class Float(Number):
"""Represent a floating-point number of arbitrary precision.
Examples
========
>>> Float(3.5)
3.50000000000000
>>> Float(3)
3.
Creating Floats from strings (and Python ``int`` type) will
give a minimum precision of 15 digits, but the precision
will automatically increase to capture all digits entered.
>>> Float(1)
1.
>>> Float(10**20)
100000000000000000000.
>>> Float('1e20')
1.e+20
However, *floating-point* numbers (Python ``float`` types) retain
only 15 digits of precision:
>>> Float(1e20)
1.00000000000000e+20
>>> Float(1.23456789123456789)
1.23456789123457
It may be preferable to enter high-precision decimal numbers
as strings:
>>> Float('1.23456789123456789')
1.23456789123456789
The desired number of digits can also be specified:
>>> Float('1e-3', 3)
0.00100
>>> Float(100, 4)
100.0
Float can automatically count significant figures if decimal precision
argument is omitted. (Auto-counting is only allowed for strings and ints).
>>> Float('12e-3')
0.012
>>> Float(3)
3.
>>> Float('60.e2') # 2 digits significant
6.0e+3
>>> Float('6000.') # 4 digits significant
6000.
>>> Float('600e-2') # 3 digits significant
6.00
Notes
=====
Floats are inexact by their nature unless their value is a binary-exact
value.
>>> approx, exact = Float(.1, 1), Float(.125, 1)
For calculation purposes, you can change the precision of Float,
but this will not increase the accuracy of the inexact value. The
following is the most accurate 5-digit approximation of a value of 0.1
that had only 1 digit of precision:
>>> Float(approx, 5)
0.099609
Please note that you can't increase precision with evalf:
>>> approx.evalf(5)
Traceback (most recent call last):
...
PrecisionExhausted: ...
By contrast, 0.125 is exact in binary (as it is in base 10) and so it
can be passed to Float constructor to obtain an arbitrary precision with
matching accuracy:
>>> Float(exact, 5)
0.12500
>>> Float(exact, 20)
0.12500000000000000000
Trying to make a high-precision Float from a float is not disallowed,
but one must keep in mind that the *underlying float* (not the apparent
decimal value) is being obtained with high precision. For example, 0.3
does not have a finite binary representation. The closest rational is
the fraction 5404319552844595/2**54. So if you try to obtain a Float of
0.3 to 20 digits of precision you will not see the same thing as 0.3
followed by 19 zeros:
>>> Float(0.3, 20)
0.29999999999999998890
If you want a 20-digit value of the decimal 0.3 (not the floating point
approximation of 0.3) you should send the 0.3 as a string. The underlying
representation is still binary but a higher precision than Python's float
is used:
>>> Float('0.3', 20)
0.30000000000000000000
Although you can increase the precision of an existing Float using Float
it will not increase the accuracy -- the underlying value is not changed:
>>> def show(f): # binary rep of Float
... from diofant import Mul, Pow
... s, m, e, b = f._mpf_
... v = Mul(int(m), Pow(2, int(e), evaluate=False), evaluate=False)
... print(f'{v} at prec={f._prec}')
...
>>> t = Float('0.3', 3)
>>> show(t)
4915/2**14 at prec=13
>>> show(Float(t, 20)) # higher prec, not higher accuracy
4915/2**14 at prec=70
>>> show(Float(t, 2)) # lower prec
307/2**10 at prec=10
"""
is_number = True
is_extended_real = True
is_Float = True
def __new__(cls, num, dps=None):
if num is oo or num == mlib.finf:
num = '+inf'
elif num == -oo or num == mlib.fninf:
num = '-inf'
elif num == nan or num == mlib.fnan:
num = 'nan'
if dps is None:
if isinstance(num, Float):
return num
elif isinstance(num, (str, numbers.Integral)):
num, dps = _str_to_Decimal_dps(str(num))
else:
dps = 15
prec = mlib.libmpf.dps_to_prec(dps)
if isinstance(num, decimal.Decimal):
_mpf_ = mlib.from_Decimal(num, prec, rnd)
elif isinstance(num, Number):
_mpf_ = num._as_mpf_val(prec)
else:
_mpf_ = mpmath.mpf(num, prec=prec, rounding=rnd)._mpf_
# special cases
if _mpf_ == mlib.fzero:
pass # we want a Float
elif _mpf_ == mlib.fnan:
return nan
obj = Expr.__new__(cls)
obj._mpf_ = _mpf_
obj._prec = prec
return obj
@classmethod
def _new(cls, _mpf_, _prec):
# special cases
if _mpf_ == mlib.fzero:
return S.Zero # XXX this is different from Float which gives 0.0
elif _mpf_ == mlib.fnan:
return nan
obj = Expr.__new__(cls)
obj._mpf_ = mpf_norm(_mpf_, _prec)
obj._prec = _prec
return obj
def __getnewargs__(self):
return self._mpf_, mlib.libmpf.prec_to_dps(self._prec)
def _hashable_content(self):
return self._mpf_, self._prec
def floor(self):
"""Compute floor of self."""
return Integer(mlib.to_int(mlib.mpf_floor(self._mpf_, self._prec)))
def ceiling(self):
"""Compute ceiling of self."""
return Integer(mlib.to_int(mlib.mpf_ceil(self._mpf_, self._prec)))
@property
def num(self):
"""Return mpmath representation."""
return mpmath.mpf(self._mpf_)
def _as_mpf_val(self, prec):
return mpf_norm(self._mpf_, prec)
def _as_mpf_op(self, prec):
return self._mpf_, max(prec, self._prec)
def _eval_is_finite(self):
return self._mpf_ not in (mlib.finf, mlib.fninf)
def _eval_is_integer(self):
return self._mpf_ == mlib.fzero
def _eval_is_positive(self):
return mlib.mpf_gt(self._mpf_, mlib.fzero)
def _eval_is_zero(self):
return self._mpf_ == mlib.fzero
def __bool__(self):
return self.is_nonzero
def __neg__(self):
return Float._new(mlib.mpf_neg(self._mpf_), self._prec)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Number):
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_add(self._mpf_, rhs, prec, rnd), prec)
return Number.__add__(self, other)
__radd__ = __add__
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Number):
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_sub(self._mpf_, rhs, prec, rnd), prec)
return Number.__sub__(self, other)
@_sympifyit('other', NotImplemented)
def __mul__(self, other):
if isinstance(other, Number):
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_mul(self._mpf_, rhs, prec, rnd), prec)
return Number.__mul__(self, other)
__rmul__ = __mul__
@_sympifyit('other', NotImplemented)
def __truediv__(self, other):
if isinstance(other, Number) and other != 0:
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_div(self._mpf_, rhs, prec, rnd), prec)
return Number.__truediv__(self, other)
@_sympifyit('other', NotImplemented)
def __mod__(self, other):
if isinstance(other, Rational) and other.denominator != 1:
# calculate mod with Rationals, *then* round the result
return Float(Rational.__mod__(Rational(self), other),
mlib.prec_to_dps(self._prec))
if isinstance(other, Float):
r = self/other
if r == int(r):
prec = max(mlib.prec_to_dps(i) for i in (self._prec, other._prec))
return Float(0, prec)
if isinstance(other, Number):
rhs, prec = other._as_mpf_op(self._prec)
return Float._new(mlib.mpf_mod(self._mpf_, rhs, prec, rnd), prec)
return Number.__mod__(self, other)
@_sympifyit('other', NotImplemented)
def __rmod__(self, other):
if isinstance(other, Float):
return other.__mod__(self)
elif isinstance(other, Rational):
# calculate mod with Rationals, *then* round the answer
return Float(other.__mod__(Rational(self)),
mlib.prec_to_dps(self._prec))
else:
return NotImplemented
def _eval_power(self, expt):
"""
Expt is symbolic object but not equal to 0, 1.
(-p)**r -> exp(r*log(-p)) -> exp(r*(log(p) + I*Pi)) ->
-> p**r*(sin(Pi*r) + cos(Pi*r)*I)
"""
from .power import Pow
if self == 0:
if expt.is_positive:
return S.Zero
if expt.is_negative:
return Float('inf')
if isinstance(expt, Number):
if isinstance(expt, Integer):
prec = self._prec
return Float._new(
mlib.mpf_pow_int(self._mpf_, expt.numerator, prec, rnd), prec)
elif isinstance(expt, Rational) and \
expt.numerator == 1 and expt.denominator % 2 and self.is_negative:
return Pow(S.NegativeOne, expt, evaluate=False)*(
-self)._eval_power(expt)
expt, prec = expt._as_mpf_op(self._prec)
mpfself = self._mpf_
try:
y = mlib.mpf_pow(mpfself, expt, prec, rnd)
return Float._new(y, prec)
except mlib.ComplexResult:
re, im = mlib.mpc_pow(
(mpfself, mlib.fzero), (expt, mlib.fzero), prec, rnd)
return Float._new(re, prec) + \
Float._new(im, prec)*I
def __abs__(self):
return Float._new(mlib.mpf_abs(self._mpf_), self._prec)
def __int__(self):
return int(mlib.to_int(self._mpf_)) # uses round_fast = round_down
def __eq__(self, other):
if isinstance(other, float):
# coerce to Float at same precision
o = Float(other)
ompf = o._as_mpf_val(self._prec)
return bool(mlib.mpf_eq(self._mpf_, ompf))
try:
other = sympify(other, strict=True)
except SympifyError:
return False # diofant != other --> not ==
if isinstance(other, NumberSymbol):
if other.is_irrational:
return False
return other.__eq__(self)
if isinstance(other, Float):
return bool(mlib.mpf_eq(self._mpf_, other._mpf_))
if isinstance(other, Number):
# numbers should compare at the same precision;
# all _as_mpf_val routines should be sure to abide
# by the request to change the prec if necessary; if
# they don't, the equality test will fail since it compares
# the mpf tuples
ompf = other._as_mpf_val(self._prec)
return bool(mlib.mpf_eq(self._mpf_, ompf))
return False # Float != non-Number
@_sympifyit('other', NotImplemented)
def __gt__(self, other):
if isinstance(other, NumberSymbol):
return other.__lt__(self)
if other.is_comparable:
other = other.evalf(strict=False)
if isinstance(other, Number) and other is not nan:
return sympify(bool(mlib.mpf_gt(self._mpf_,
other._as_mpf_val(self._prec))),
strict=True)
return Expr.__gt__(self, other)
@_sympifyit('other', NotImplemented)
def __ge__(self, other):
if isinstance(other, NumberSymbol):
return other.__le__(self)
if other.is_comparable:
other = other.evalf(strict=False)
if isinstance(other, Number) and other is not nan:
return sympify(bool(mlib.mpf_ge(self._mpf_,
other._as_mpf_val(self._prec))),
strict=True)
return Expr.__ge__(self, other)
@_sympifyit('other', NotImplemented)
def __lt__(self, other):
if isinstance(other, NumberSymbol):
return other.__gt__(self)
if other.is_extended_real and other.is_number:
other = other.evalf(strict=False)
if isinstance(other, Number) and other is not nan:
return sympify(bool(mlib.mpf_lt(self._mpf_,
other._as_mpf_val(self._prec))),
strict=True)
return Expr.__lt__(self, other)
@_sympifyit('other', NotImplemented)
def __le__(self, other):
if isinstance(other, NumberSymbol):
return other.__ge__(self)
if other.is_extended_real and other.is_number:
other = other.evalf(strict=False)
if isinstance(other, Number) and other is not nan:
return sympify(bool(mlib.mpf_le(self._mpf_,
other._as_mpf_val(self._prec))),
strict=True)
return Expr.__le__(self, other)
def __hash__(self):
return super().__hash__()
def epsilon_eq(self, other, epsilon='1e-15'):
"""Test approximate equality."""
return abs(self - other) < Float(epsilon)
def __format__(self, format_spec):
return format(decimal.Decimal(str(self)), format_spec)
# Ground type for components of Rational
_int_dtype = gmpy.mpz if GROUND_TYPES == 'gmpy' else int
class Rational(Number):
"""Represents integers and rational numbers (p/q) of any size.
Examples
========
>>> Rational(3)
3
>>> Rational(1, 2)
1/2
Rational is unprejudiced in accepting input. If a float is passed, the
underlying value of the binary representation will be returned:
>>> Rational(.5)
1/2
>>> Rational(.2)
3602879701896397/18014398509481984
If the simpler representation of the float is desired then consider
limiting the denominator to the desired value or convert the float to
a string (which is roughly equivalent to limiting the denominator to
10**12):
>>> Rational(str(.2))
1/5
>>> Rational(.2).limit_denominator(10**12)
1/5
An arbitrarily precise Rational is obtained when a string literal is
passed:
>>> Rational('1.23')
123/100
>>> Rational('1e-2')
1/100
>>> Rational('.1')
1/10
The conversion of floats to expressions or simple fractions can
be handled with nsimplify:
>>> nsimplify(.3) # numbers that have a simple form
3/10
But if the input does not reduce to a literal Rational, an error will
be raised:
>>> Rational(pi)
Traceback (most recent call last):
...
TypeError: invalid input: pi
Low-level access numerator and denominator:
>>> r = Rational(3, 4)
>>> r
3/4
>>> r.numerator
3
>>> r.denominator
4
Note that these properties return integers (not Diofant Integers) so some care
is needed when using them in expressions:
>>> r.numerator/r.denominator
0.75
See Also
========
diofant.core.sympify.sympify
diofant.simplify.simplify.nsimplify
"""
is_real = True
is_integer = False
is_rational = True
is_number = True
is_Rational = True
@cacheit
def __new__(cls, p, q=1):
if q == 1:
if isinstance(p, Rational):
return p
elif isinstance(p, Float):
with mpmath.workprec(p._prec):
p, q = mlib.to_rational(p._mpf_)
try:
f = fractions.Fraction(p)/fractions.Fraction(q)
p, q = f.numerator, f.denominator
except ValueError:
raise TypeError(f'invalid input: {p}, {q}')
except ZeroDivisionError:
if p == 0:
return nan
else:
return zoo
if q == 1:
return Integer(p)
if p == 1 and q == 2:
return S.Half
obj = Expr.__new__(cls)
obj._numerator = _int_dtype(p)
obj._denominator = _int_dtype(q)
return obj
def limit_denominator(self, max_denominator=1000000):
"""Closest Rational to self with denominator at most max_denominator.
>>> Rational('3.141592653589793').limit_denominator(10)
22/7
>>> Rational('3.141592653589793').limit_denominator(100)
311/99
"""
f = fractions.Fraction(self.numerator, self.denominator)
return Rational(f.limit_denominator(max_denominator))
def __getnewargs__(self):
return self.numerator, self.denominator
def _hashable_content(self):
return self.numerator, self.denominator
def _eval_is_positive(self):
return self.numerator > 0
def _eval_is_zero(self):
return self.numerator == 0
def __bool__(self):
return self.is_nonzero
def __neg__(self):
return Rational(-self.numerator, self.denominator)
@_sympifyit('other', NotImplemented)
def __add__(self, other):
if isinstance(other, Rational):
n, d = other.numerator, other.denominator
return Rational(self.numerator*d + self.denominator*n, self.denominator*d)
else:
return other.__radd__(self)
@_sympifyit('other', NotImplemented)
def __sub__(self, other):
if isinstance(other, Rational):