This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
other.py
2244 lines (1820 loc) · 65.1 KB
/
other.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
"""
Other functions
TESTS:
Check that gamma function imports are deprecated (:trac:`24411`)::
sage: from sage.functions.other import beta
sage: beta(x, x)
doctest:warning...: DeprecationWarning:
Importing beta from here is deprecated; please use "from sage.functions.gamma import beta" instead.
See http://trac.sagemath.org/24411 for details.
beta(x, x)
"""
from sage.misc.lazy_import import lazy_import
lazy_import('sage.functions.gamma',
('gamma', 'log_gamma', 'gamma_inc',
'gamma_inc_lower', 'psi', 'beta'), deprecation=24411)
from sage.symbolic.function import GinacFunction, BuiltinFunction
from sage.symbolic.expression import Expression, register_symbol, symbol_table
from sage.symbolic.ring import SR, SymbolicRing
from sage.rings.integer import Integer
from sage.rings.integer_ring import ZZ
from sage.rings.rational import Rational
from sage.rings.complex_mpfr import ComplexField
from sage.misc.latex import latex
from sage.structure.element import Element
import math
from sage.structure.element import coercion_model
# avoid name conflicts with `parent` as a function parameter
from sage.structure.all import parent as s_parent
from sage.functions.trig import arctan2
from sage.arith.misc import binomial as arith_binomial
from sage.misc.functional import sqrt
class Function_abs(GinacFunction):
def __init__(self):
r"""
The absolute value function.
EXAMPLES::
sage: var('x y')
(x, y)
sage: abs(x)
abs(x)
sage: abs(x^2 + y^2)
abs(x^2 + y^2)
sage: abs(-2)
2
sage: sqrt(x^2)
sqrt(x^2)
sage: abs(sqrt(x))
sqrt(abs(x))
sage: complex(abs(3*I))
(3+0j)
sage: f = sage.functions.other.Function_abs()
sage: latex(f)
\mathrm{abs}
sage: latex(abs(x))
{\left| x \right|}
sage: abs(x)._sympy_()
Abs(x)
Test pickling::
sage: loads(dumps(abs(x)))
abs(x)
TESTS:
Check that :trac:`12588` is fixed::
sage: abs(pi*I)
pi
sage: abs(pi*I*catalan)
catalan*pi
sage: abs(pi*catalan*x)
catalan*pi*abs(x)
sage: abs(pi*I*catalan*x)
catalan*pi*abs(x)
sage: abs(1.0j*pi)
1.00000000000000*pi
sage: abs(I*x)
abs(x)
sage: abs(I*pi)
pi
sage: abs(I*log(2))
log(2)
sage: abs(I*e^5)
e^5
sage: abs(log(1/2))
-log(1/2)
sage: abs(log(3/2))
log(3/2)
sage: abs(log(1/2)*log(1/3))
log(1/2)*log(1/3)
sage: abs(log(1/2)*log(1/3)*log(1/4))
-log(1/2)*log(1/3)*log(1/4)
sage: abs(log(1/2)*log(1/3)*log(1/4)*i)
-log(1/2)*log(1/3)*log(1/4)
sage: abs(log(x))
abs(log(x))
sage: abs(zeta(I))
abs(zeta(I))
sage: abs(e^2*x)
abs(x)*e^2
sage: abs((pi+e)*x)
(pi + e)*abs(x)
sage: fricas(abs(x)).sage().derivative() # optional - fricas
1/2*(x + conjugate(x))/abs(x)
"""
GinacFunction.__init__(self, "abs", latex_name=r"\mathrm{abs}",
conversions=dict(sympy='Abs',
mathematica='Abs',
giac='abs',
fricas='abs'))
abs = abs_symbolic = Function_abs()
def _eval_floor_ceil(self, x, method, bits=0, **kwds):
"""
Helper function to compute ``floor(x)`` or ``ceil(x)``.
INPUT:
- ``x`` -- a number
- ``method`` -- should be either ``"floor"`` or ``"ceil"``
- ``bits`` -- how many bits to use before giving up
See :class:`Function_floor` and :class:`Function_ceil` for examples
and tests.
TESTS::
sage: numbers = [SR(10^100 + exp(-100)), SR(10^100 - exp(-100)), SR(10^100)]
sage: numbers += [-n for n in numbers]
sage: for n in numbers:
....: f = floor(n)
....: c = ceil(n)
....: if f == c:
....: assert n in ZZ
....: else:
....: assert f + 1 == c
A test from :trac:`12121`::
sage: e1 = pi - continued_fraction(pi).convergent(2785)
sage: e2 = e - continued_fraction(e).convergent(1500)
sage: f = e1/e2
sage: f = 1 / (f - continued_fraction(f).convergent(1000))
sage: f = f - continued_fraction(f).convergent(1)
sage: floor(f, bits=10000)
-1
sage: ceil(f, bits=10000)
0
These do not work but fail gracefully::
sage: ceil(Infinity)
Traceback (most recent call last):
...
ValueError: Calling ceil() on infinity or NaN
sage: ceil(NaN)
Traceback (most recent call last):
...
ValueError: Calling ceil() on infinity or NaN
Test that elements of symbolic subrings work in the same way as
elements of ``SR``, :trac:`32724`::
sage: SCR = SR.subring(no_variables=True)
sage: floor(log(2^(3/2)) / log(2) + 1/2)
2
sage: floor(SCR(log(2^(-3/2)) / log(2) + 1/2))
-1
"""
# First, some obvious things...
try:
m = getattr(x, method)
except AttributeError:
pass
else:
return m()
if isinstance(x, int):
return Integer(x)
if isinstance(x, (float, complex)):
m = getattr(math, method)
return Integer(m(x))
if type(x).__module__ == 'numpy':
import numpy
m = getattr(numpy, method)
return m(x)
# The strategy is to convert the number to an interval field and
# hope that this interval will have a unique floor/ceiling.
#
# There are 2 reasons why this could fail:
# (A) The expression is very complicated and we simply require
# more bits.
# (B) The expression is a non-obvious exact integer. In this
# case, adding bits will not help since an interval around
# an integer will not have a unique floor/ceiling, no matter
# how many bits are used.
#
# The strategy is to first reduce the absolute diameter of the
# interval until its size is at most 10^(-6). Then we check for
# (B) by simplifying the expression.
from sage.rings.real_mpfi import RealIntervalField
# Might it be needed to simplify x? This only applies for
# elements of SR (or its subrings)
need_to_simplify = isinstance(s_parent(x), SymbolicRing)
# An integer which is close to x. We use this to increase precision
# by subtracting this guess before converting to an interval field.
# This mostly helps with the case that x is close to, but not equal
# to, an exact integer.
guess = Integer(0)
# We do not use the target number of bits immediately, we just use
# it as indication of when to stop.
target_bits = bits
bits = 32
attempts = 5
while attempts:
attempts -= 1
if not attempts and bits < target_bits:
# Add one more attempt as long as the precision is less
# than requested
attempts = 1
RIF = RealIntervalField(bits)
if guess:
y = x - guess
else:
y = x
try:
y_interval = RIF(y)
except TypeError:
# If we cannot compute a numerical enclosure, leave the
# expression unevaluated.
return BuiltinFunction.__call__(self, SR(x))
diam = y_interval.absolute_diameter()
if diam.is_infinity():
# We have a very bad approximation => increase the number
# of bits a lot
bits *= 4
continue
fdiam = float(diam)
if fdiam >= 1.0:
# Increase number of bits to get to a diameter less than
# 2^(-32), assuming that the diameter scales as 2^(-bits)
bits += 32 + int(diam.log2())
continue
# Compute ceil/floor of both ends of the interval:
# if these match, we are done!
a = getattr(y_interval.lower(), method)()
b = getattr(y_interval.upper(), method)()
if a == b:
return a + guess
# Compute a better guess for the next attempt. Since diam < 1,
# there is a unique integer in our interval. This integer equals
# the ceil of the lower bound and the floor of the upper bound.
if self is floor:
guess += b
else:
assert self is ceil
guess += a
if need_to_simplify and fdiam <= 1e-6:
x = x.full_simplify().canonicalize_radical()
need_to_simplify = False
continue
bits *= 2
raise ValueError("cannot compute {}({!r}) using {} bits of precision".format(method, x, RIF.precision()))
class Function_ceil(BuiltinFunction):
def __init__(self):
r"""
The ceiling function.
The ceiling of `x` is computed in the following manner.
#. The ``x.ceil()`` method is called and returned if it
is there. If it is not, then Sage checks if `x` is one of
Python's native numeric data types. If so, then it calls and
returns ``Integer(math.ceil(x))``.
#. Sage tries to convert `x` into a
``RealIntervalField`` with 53 bits of precision. Next,
the ceilings of the endpoints are computed. If they are the same,
then that value is returned. Otherwise, the precision of the
``RealIntervalField`` is increased until they do match
up or it reaches ``bits`` of precision.
#. If none of the above work, Sage returns a
``Expression`` object.
EXAMPLES::
sage: a = ceil(2/5 + x)
sage: a
ceil(x + 2/5)
sage: a(x=4)
5
sage: a(x=4.0)
5
sage: ZZ(a(x=3))
4
sage: a = ceil(x^3 + x + 5/2); a
ceil(x^3 + x + 5/2)
sage: a.simplify()
ceil(x^3 + x + 1/2) + 2
sage: a(x=2)
13
::
sage: ceil(sin(8)/sin(2))
2
::
sage: ceil(5.4)
6
sage: type(ceil(5.4))
<class 'sage.rings.integer.Integer'>
::
sage: ceil(factorial(50)/exp(1))
11188719610782480504630258070757734324011354208865721592720336801
sage: ceil(SR(10^50 + 10^(-50)))
100000000000000000000000000000000000000000000000001
sage: ceil(SR(10^50 - 10^(-50)))
100000000000000000000000000000000000000000000000000
Small numbers which are extremely close to an integer are hard to
deal with::
sage: ceil((33^100 + 1)^(1/100))
Traceback (most recent call last):
...
ValueError: cannot compute ceil(...) using 256 bits of precision
This can be fixed by giving a sufficiently large ``bits`` argument::
sage: ceil((33^100 + 1)^(1/100), bits=500)
Traceback (most recent call last):
...
ValueError: cannot compute ceil(...) using 512 bits of precision
sage: ceil((33^100 + 1)^(1/100), bits=1000)
34
::
sage: ceil(sec(e))
-1
sage: latex(ceil(x))
\left \lceil x \right \rceil
sage: ceil(x)._sympy_()
ceiling(x)
::
sage: import numpy
sage: a = numpy.linspace(0,2,6)
sage: ceil(a)
array([0., 1., 1., 2., 2., 2.])
Test pickling::
sage: loads(dumps(ceil))
ceil
"""
BuiltinFunction.__init__(self, "ceil",
conversions=dict(maxima='ceiling',
sympy='ceiling',
giac='ceil'))
def _print_latex_(self, x):
r"""
EXAMPLES::
sage: latex(ceil(x)) # indirect doctest
\left \lceil x \right \rceil
"""
return r"\left \lceil %s \right \rceil"%latex(x)
#FIXME: this should be moved to _eval_
def __call__(self, x, **kwds):
"""
Allows an object of this class to behave like a function. If
``ceil`` is an instance of this class, we can do ``ceil(n)`` to get
the ceiling of ``n``.
TESTS::
sage: ceil(SR(10^50 + 10^(-50)))
100000000000000000000000000000000000000000000000001
sage: ceil(SR(10^50 - 10^(-50)))
100000000000000000000000000000000000000000000000000
sage: ceil(int(10^50))
100000000000000000000000000000000000000000000000000
sage: ceil((1725033*pi - 5419351)/(25510582*pi - 80143857))
-2
"""
return _eval_floor_ceil(self, x, "ceil", **kwds)
def _eval_(self, x):
"""
EXAMPLES::
sage: ceil(x).subs(x==7.5)
8
sage: ceil(x)
ceil(x)
sage: var('x',domain='integer')
x
sage: ceil(x)
x
sage: ceil(factorial(x) + binomial(x^2, x))
binomial(x^2, x) + factorial(x)
sage: ceil(gamma(abs(2*x)+1) * real(x))
x*gamma(2*abs(x) + 1)
sage: forget()
"""
try:
if SR(x).variables() and x.is_integer():
return x
except TypeError:
pass
try:
return x.ceil()
except AttributeError:
if isinstance(x, int):
return Integer(x)
elif isinstance(x, (float, complex)):
return Integer(math.ceil(x))
return None
ceil = Function_ceil()
class Function_floor(BuiltinFunction):
def __init__(self):
r"""
The floor function.
The floor of `x` is computed in the following manner.
#. The ``x.floor()`` method is called and returned if
it is there. If it is not, then Sage checks if `x` is one
of Python's native numeric data types. If so, then it calls and
returns ``Integer(math.floor(x))``.
#. Sage tries to convert `x` into a
``RealIntervalField`` with 53 bits of precision. Next,
the floors of the endpoints are computed. If they are the same,
then that value is returned. Otherwise, the precision of the
``RealIntervalField`` is increased until they do match
up or it reaches ``bits`` of precision.
#. If none of the above work, Sage returns a
symbolic ``Expression`` object.
EXAMPLES::
sage: floor(5.4)
5
sage: type(floor(5.4))
<class 'sage.rings.integer.Integer'>
sage: var('x')
x
sage: a = floor(5.4 + x); a
floor(x + 5.40000000000000)
sage: a.simplify()
floor(x + 0.4000000000000004) + 5
sage: a(x=2)
7
::
sage: floor(cos(8) / cos(2))
0
sage: floor(log(4) / log(2))
2
sage: a = floor(5.4 + x); a
floor(x + 5.40000000000000)
sage: a.subs(x==2)
7
sage: floor(log(2^(3/2)) / log(2) + 1/2)
2
sage: floor(log(2^(-3/2)) / log(2) + 1/2)
-1
::
sage: floor(factorial(50)/exp(1))
11188719610782480504630258070757734324011354208865721592720336800
sage: floor(SR(10^50 + 10^(-50)))
100000000000000000000000000000000000000000000000000
sage: floor(SR(10^50 - 10^(-50)))
99999999999999999999999999999999999999999999999999
sage: floor(int(10^50))
100000000000000000000000000000000000000000000000000
Small numbers which are extremely close to an integer are hard to
deal with::
sage: floor((33^100 + 1)^(1/100))
Traceback (most recent call last):
...
ValueError: cannot compute floor(...) using 256 bits of precision
This can be fixed by giving a sufficiently large ``bits`` argument::
sage: floor((33^100 + 1)^(1/100), bits=500)
Traceback (most recent call last):
...
ValueError: cannot compute floor(...) using 512 bits of precision
sage: floor((33^100 + 1)^(1/100), bits=1000)
33
::
sage: import numpy
sage: a = numpy.linspace(0,2,6)
sage: floor(a)
array([0., 0., 0., 1., 1., 2.])
sage: floor(x)._sympy_()
floor(x)
Test pickling::
sage: loads(dumps(floor))
floor
"""
BuiltinFunction.__init__(self, "floor",
conversions=dict(sympy='floor', giac='floor'))
def _print_latex_(self, x):
r"""
EXAMPLES::
sage: latex(floor(x))
\left \lfloor x \right \rfloor
"""
return r"\left \lfloor %s \right \rfloor"%latex(x)
#FIXME: this should be moved to _eval_
def __call__(self, x, **kwds):
"""
Allows an object of this class to behave like a function. If
``floor`` is an instance of this class, we can do ``floor(n)`` to
obtain the floor of ``n``.
TESTS::
sage: floor(SR(10^50 + 10^(-50)))
100000000000000000000000000000000000000000000000000
sage: floor(SR(10^50 - 10^(-50)))
99999999999999999999999999999999999999999999999999
sage: floor(int(10^50))
100000000000000000000000000000000000000000000000000
sage: floor((1725033*pi - 5419351)/(25510582*pi - 80143857))
-3
"""
return _eval_floor_ceil(self, x, "floor", **kwds)
def _eval_(self, x):
"""
EXAMPLES::
sage: floor(x).subs(x==7.5)
7
sage: floor(x)
floor(x)
sage: var('x',domain='integer')
x
sage: floor(x)
x
sage: floor(factorial(x) + binomial(x^2, x))
binomial(x^2, x) + factorial(x)
sage: floor(gamma(abs(2*x)+1) * real(x))
x*gamma(2*abs(x) + 1)
sage: forget()
"""
try:
if SR(x).variables() and x.is_integer():
return x
except TypeError:
pass
try:
return x.floor()
except AttributeError:
if isinstance(x, int):
return Integer(x)
elif isinstance(x, (float, complex)):
return Integer(math.floor(x))
return None
floor = Function_floor()
class Function_Order(GinacFunction):
def __init__(self):
r"""
The order function.
This function gives the order of magnitude of some expression,
similar to `O`-terms.
.. SEEALSO::
:meth:`~sage.symbolic.expression.Expression.Order`,
:mod:`~sage.rings.big_oh`
EXAMPLES::
sage: x = SR('x')
sage: x.Order()
Order(x)
sage: (x^2 + x).Order()
Order(x^2 + x)
TESTS:
Check that :trac:`19425` is resolved::
sage: x.Order().operator()
Order
"""
GinacFunction.__init__(self, "Order",
conversions=dict(),
latex_name=r"\mathcal{O}")
def _sympy_(self, arg):
"""
EXAMPLES::
sage: x.Order()._sympy_()
O(x)
sage: SR(1).Order()._sympy_()
O(1)
sage: ((x-1)^3).Order()._sympy_()
O((x - 1)**3, (x, 1))
sage: exp(x).series(x==1, 3)._sympy_()
E + E*(x - 1) + E*(x - 1)**2/2 + O((x - 1)**3, (x, 1))
sage: (-(pi-x)^3).Order()._sympy_()
O((x - pi)**3, (x, pi))
sage: cos(x).series(x==pi, 3)._sympy_()
-1 + (pi - x)**2/2 + O((x - pi)**3, (x, pi))
"""
roots = arg.solve(arg.default_variable(), algorithm='sympy',
multiplicities=False, explicit_solutions=True)
if len(roots) == 1:
arg = (arg, (roots[0].lhs(), roots[0].rhs()))
elif len(roots) > 1:
raise ValueError("order term %s has multiple roots" % arg)
# else there are no roots, e.g. O(1), so we leave arg unchanged
import sympy
return sympy.O(*sympy.sympify(arg, evaluate=False))
Order = Function_Order()
class Function_frac(BuiltinFunction):
def __init__(self):
r"""
The fractional part function `\{x\}`.
``frac(x)`` is defined as `\{x\} = x - \lfloor x\rfloor`.
EXAMPLES::
sage: frac(5.4)
0.400000000000000
sage: type(frac(5.4))
<class 'sage.rings.real_mpfr.RealNumber'>
sage: frac(456/123)
29/41
sage: var('x')
x
sage: a = frac(5.4 + x); a
frac(x + 5.40000000000000)
sage: frac(cos(8)/cos(2))
cos(8)/cos(2)
sage: latex(frac(x))
\operatorname{frac}\left(x\right)
sage: frac(x)._sympy_()
frac(x)
Test pickling::
sage: loads(dumps(floor))
floor
"""
BuiltinFunction.__init__(self, "frac",
conversions=dict(sympy='frac'),
latex_name=r"\operatorname{frac}")
def _evalf_(self, x, **kwds):
"""
EXAMPLES::
sage: frac(pi).n()
0.141592653589793
sage: frac(pi).n(200)
0.14159265358979323846264338327950288419716939937510582097494
"""
return x - floor(x)
def _eval_(self, x):
"""
EXAMPLES::
sage: frac(x).subs(x==7.5)
0.500000000000000
sage: frac(x)
frac(x)
"""
try:
return x - x.floor()
except AttributeError:
if isinstance(x, int):
return Integer(0)
elif isinstance(x, (float, complex)):
return x - Integer(math.floor(x))
elif isinstance(x, Expression):
ret = floor(x)
if not hasattr(ret, "operator") or not ret.operator() == floor:
return x - ret
return None
frac = Function_frac()
# register sqrt in pynac symbol_table for conversion back from other systems
register_symbol(sqrt, dict(mathematica='Sqrt'), 2)
symbol_table['functions']['sqrt'] = sqrt
Function_sqrt = type('deprecated_sqrt', (),
{'__call__': staticmethod(sqrt),
'__setstate__': lambda x, y: None})
class Function_real_nth_root(BuiltinFunction):
r"""
Real `n`-th root function `x^\frac{1}{n}`.
The function assumes positive integer `n` and real number `x`.
EXAMPLES::
sage: real_nth_root(2, 3)
2^(1/3)
sage: real_nth_root(-2, 3)
-2^(1/3)
sage: real_nth_root(8, 3)
2
sage: real_nth_root(-8, 3)
-2
sage: real_nth_root(-2, 4)
Traceback (most recent call last):
...
ValueError: no real nth root of negative real number with even n
For numeric input, it gives a numerical approximation. ::
sage: real_nth_root(2., 3)
1.25992104989487
sage: real_nth_root(-2., 3)
-1.25992104989487
Some symbolic calculus::
sage: f = real_nth_root(x, 5)^3
sage: f
real_nth_root(x^3, 5)
sage: f.diff()
3/5*x^2*real_nth_root(x^(-12), 5)
sage: result = f.integrate(x)
...
sage: result
integrate((abs(x)^3)^(1/5)*sgn(x^3), x)
sage: _.diff()
(abs(x)^3)^(1/5)*sgn(x^3)
"""
def __init__(self):
r"""
Initialize.
TESTS::
sage: cube_root = real_nth_root(x, 3)
sage: loads(dumps(cube_root))
real_nth_root(x, 3)
::
sage: f = real_nth_root(x, 3)
sage: f._sympy_()
Piecewise((Abs(x)**(1/3)*sign(x), Eq(im(x), 0)), (x**(1/3), True))
"""
BuiltinFunction.__init__(self, "real_nth_root", nargs=2,
conversions=dict(sympy='real_root',
mathematica='Surd',
maple='surd'))
def _print_latex_(self, base, exp):
r"""
TESTS::
sage: latex(real_nth_root(x, 3))
x^{\frac{1}{3}}
sage: latex(real_nth_root(x^2 + x, 3))
{\left(x^{2} + x\right)}^{\frac{1}{3}}
"""
return latex(base**(1/exp))
def _evalf_(self, base, exp, parent=None):
"""
TESTS::
sage: real_nth_root(RDF(-2), 3)
-1.25992104989487...
sage: real_nth_root(Reals(100)(2), 2)
1.4142135623730950488016887242
"""
if hasattr(exp, 'real_part'):
# To allow complex "noise" while plotting, the fast_callable()
# interpreters used in plots will convert all intermediate
# expressions to CDF, returning only the final answer as a
# real number. However, for a symbolic function such as this,
# the "exp" argument is in fact an intermediate expression.
# Thus we are forced to deal with exponents of the form
# (n + 0*I), which a priori will throw a TypeError at the "%"
# below. Here we special-case only CDF and CC, leaving the
# python "complex" type unhandled: you have to try very hard
# to pass a python "complex" in as an exponent, and the extra
# effort/slowdown doesn't seem worth it.
if exp.imag_part().is_zero():
exp = exp.real_part()
else:
raise ValueError("exponent cannot be complex")
exp = ZZ(exp)
negative = base < 0
if negative:
if exp.mod(2) == 0:
raise ValueError('no real nth root of negative real number with even n')
base = -base
r = base**(1/exp)
if negative:
return -r
else:
return r
def _eval_(self, base, exp):
"""
TESTS::
sage: real_nth_root(x, 1)
x
sage: real_nth_root(x, 3)
real_nth_root(x, 3)
sage: real_nth_root(RIF(2), 3)
1.259921049894873?
sage: real_nth_root(RBF(2), 3)
[1.259921049894873 +/- 3.92e-16]
"""
if not isinstance(base, Expression) and not isinstance(exp, Expression):
if isinstance(base, Integer):
try:
return base.nth_root(exp)
except ValueError:
pass
return self._evalf_(base, exp, parent=s_parent(base))
if isinstance(exp, Integer) and exp.is_one():
return base
def _power_(self, base, exp, power_param=None):
"""
TESTS::
sage: f = real_nth_root(x, 3)
sage: f^5
real_nth_root(x^5, 3)
"""
return self(base**power_param, exp)
def _derivative_(self, base, exp, diff_param=None):
"""
TESTS::
sage: f = real_nth_root(x, 3)
sage: f.diff()
1/3*real_nth_root(x^(-2), 3)
sage: f = real_nth_root(-x, 3)
sage: f.diff()
-1/3*real_nth_root(x^(-2), 3)
sage: f = real_nth_root(x, 4)
sage: f.diff()
1/4*real_nth_root(x^(-3), 4)
sage: f = real_nth_root(-x, 4)
sage: f.diff()
-1/4*real_nth_root(-1/x^3, 4)
"""
return 1/exp * self(base, exp)**(1-exp)
real_nth_root = Function_real_nth_root()
class Function_arg(BuiltinFunction):
def __init__(self):
r"""
The argument function for complex numbers.
EXAMPLES::
sage: arg(3+i)
arctan(1/3)
sage: arg(-1+i)
3/4*pi
sage: arg(2+2*i)
1/4*pi
sage: arg(2+x)
arg(x + 2)
sage: arg(2.0+i+x)
arg(x + 2.00000000000000 + 1.00000000000000*I)
sage: arg(-3)
pi
sage: arg(3)
0
sage: arg(0)
0
sage: latex(arg(x))
{\rm arg}\left(x\right)
sage: maxima(arg(x))
atan2(0,_SAGE_VAR_x)
sage: maxima(arg(2+i))
atan(1/2)
sage: maxima(arg(sqrt(2)+i))
atan(1/sqrt(2))
sage: arg(x)._sympy_()
arg(x)
sage: arg(2+i)
arctan(1/2)
sage: arg(sqrt(2)+i)
arg(sqrt(2) + I)
sage: arg(sqrt(2)+i).simplify()
arctan(1/2*sqrt(2))
TESTS::
sage: arg(0.0)
0.000000000000000
sage: arg(3.0)
0.000000000000000
sage: arg(-2.5)
3.14159265358979
sage: arg(2.0+3*i)