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
/
expression.pyx
10826 lines (8712 loc) · 338 KB
/
expression.pyx
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
"""
Symbolic Expressions
RELATIONAL EXPRESSIONS:
We create a relational expression::
sage: x = var('x')
sage: eqn = (x-1)^2 <= x^2 - 2*x + 3
sage: eqn.subs(x == 5)
16 <= 18
Notice that squaring the relation squares both sides.
::
sage: eqn^2
(x - 1)^4 <= (x^2 - 2*x + 3)^2
sage: eqn.expand()
x^2 - 2*x + 1 <= x^2 - 2*x + 3
The can transform a true relational into a false one::
sage: eqn = SR(-5) < SR(-3); eqn
-5 < -3
sage: bool(eqn)
True
sage: eqn^2
25 < 9
sage: bool(eqn^2)
False
We can do arithmetic with relationals::
sage: e = x+1 <= x-2
sage: e + 2
x + 3 <= x
sage: e - 1
x <= x - 3
sage: e*(-1)
-x - 1 <= -x + 2
sage: (-2)*e
-2*x - 2 <= -2*x + 4
sage: e*5
5*x + 5 <= 5*x - 10
sage: e/5
1/5*x + 1/5 <= 1/5*x - 2/5
sage: 5/e
5/(x + 1) <= 5/(x - 2)
sage: e/(-2)
-1/2*x - 1/2 <= -1/2*x + 1
sage: -2/e
-2/(x + 1) <= -2/(x - 2)
We can even add together two relations, so long as the operators are
the same::
sage: (x^3 + x <= x - 17) + (-x <= x - 10)
x^3 <= 2*x - 27
Here they are not::
sage: (x^3 + x <= x - 17) + (-x >= x - 10)
Traceback (most recent call last):
...
TypeError: incompatible relations
ARBITRARY SAGE ELEMENTS:
You can work symbolically with any Sage data type. This can lead to
nonsense if the data type is strange, e.g., an element of a finite
field (at present).
We mix Singular variables with symbolic variables::
sage: R.<u,v> = QQ[]
sage: var('a,b,c')
(a, b, c)
sage: expand((u + v + a + b + c)^2)
a^2 + 2*a*b + b^2 + 2*a*c + 2*b*c + c^2 + 2*a*u + 2*b*u + 2*c*u + u^2 + 2*a*v + 2*b*v + 2*c*v + 2*u*v + v^2
TESTS:
Test Jacobian on Pynac expressions. (:trac:`5546`) ::
sage: var('x,y')
(x, y)
sage: f = x + y
sage: jacobian(f, [x,y])
[1 1]
Test if matrices work (:trac:`5546`) ::
sage: var('x,y,z')
(x, y, z)
sage: M = matrix(2,2,[x,y,z,x])
sage: v = vector([x,y])
sage: M * v
(x^2 + y^2, x*y + x*z)
sage: v*M
(x^2 + y*z, 2*x*y)
Test if comparison bugs from :trac:`6256` are fixed::
sage: t = exp(sqrt(x)); u = 1/t
sage: t*u
1
sage: t + u
e^(-sqrt(x)) + e^sqrt(x)
sage: t
e^sqrt(x)
Test if :trac:`9947` is fixed::
sage: real_part(1+2*(sqrt(2)+1)*(sqrt(2)-1))
3
sage: a=(sqrt(4*(sqrt(3) - 5)*(sqrt(3) + 5) + 48) + 4*sqrt(3))/ (sqrt(3) + 5)
sage: a.real_part()
4*sqrt(3)/(sqrt(3) + 5)
sage: a.imag_part()
sqrt(abs(4*(sqrt(3) + 5)*(sqrt(3) - 5) + 48))/(sqrt(3) + 5)
"""
###############################################################################
# Sage: Open Source Mathematical Software
# Copyright (C) 2008 William Stein <wstein@gmail.com>
# Copyright (C) 2008 Burcin Erocal <burcin@erocal.org>
# Distributed under the terms of the GNU General Public License (GPL),
# version 2 or any later version. The full text of the GPL is available at:
# http://www.gnu.org/licenses/
###############################################################################
include "sage/ext/interrupt.pxi"
include "sage/ext/stdsage.pxi"
include "sage/ext/cdefs.pxi"
include "sage/ext/python.pxi"
import operator
import ring
import sage.rings.integer
import sage.rings.rational
from sage.structure.element cimport ModuleElement, RingElement, Element
from sage.symbolic.getitem cimport OperandsWrapper
from sage.symbolic.complexity_measures import string_length
from sage.symbolic.function import get_sfunction_from_serial, SymbolicFunction
from sage.rings.rational import Rational # Used for sqrt.
from sage.misc.derivative import multi_derivative
from sage.misc.superseded import deprecated_function_alias
from sage.rings.infinity import AnInfinity, infinity, minus_infinity, unsigned_infinity
from sage.misc.decorators import rename_keyword
from sage.structure.dynamic_class import dynamic_class
# a small overestimate of log(10,2)
LOG_TEN_TWO_PLUS_EPSILON = 3.321928094887363
cpdef bint is_Expression(x):
"""
Return True if *x* is a symbolic Expression.
EXAMPLES::
sage: from sage.symbolic.expression import is_Expression
sage: is_Expression(x)
True
sage: is_Expression(2)
False
sage: is_Expression(SR(2))
True
"""
return isinstance(x, Expression)
cpdef bint is_SymbolicEquation(x):
"""
Return True if *x* is a symbolic equation.
EXAMPLES:
The following two examples are symbolic equations::
sage: from sage.symbolic.expression import is_SymbolicEquation
sage: is_SymbolicEquation(sin(x) == x)
True
sage: is_SymbolicEquation(sin(x) < x)
True
sage: is_SymbolicEquation(x)
False
This is not, since ``2==3`` evaluates to the boolean
``False``::
sage: is_SymbolicEquation(2 == 3)
False
However here since both 2 and 3 are coerced to be symbolic, we
obtain a symbolic equation::
sage: is_SymbolicEquation(SR(2) == SR(3))
True
"""
return isinstance(x, Expression) and is_a_relational((<Expression>x)._gobj)
cdef class Expression(CommutativeRingElement):
cpdef object pyobject(self):
"""
Get the underlying Python object.
OUTPUT:
The Python object corresponding to this expression, assuming
this expression is a single numerical value or an infinity
representable in Python. Otherwise, a ``TypeError`` is raised.
EXAMPLES::
sage: var('x')
x
sage: b = -17/3
sage: a = SR(b)
sage: a.pyobject()
-17/3
sage: a.pyobject() is b
True
TESTS::
sage: SR(oo).pyobject()
+Infinity
sage: SR(-oo).pyobject()
-Infinity
sage: SR(unsigned_infinity).pyobject()
Infinity
sage: SR(I*oo).pyobject()
Traceback (most recent call last):
...
TypeError: Python infinity cannot have complex phase.
"""
cdef GConstant* c
if is_a_constant(self._gobj):
from sage.symbolic.constants import constants_name_table
return constants_name_table[GEx_to_str(&self._gobj)]
if is_a_infinity(self._gobj):
if (ex_to_infinity(self._gobj).is_unsigned_infinity()): return unsigned_infinity
if (ex_to_infinity(self._gobj).is_plus_infinity()): return infinity
if (ex_to_infinity(self._gobj).is_minus_infinity()): return minus_infinity
raise TypeError('Python infinity cannot have complex phase.')
if not is_a_numeric(self._gobj):
raise TypeError("self must be a numeric expression")
return py_object_from_numeric(self._gobj)
def __init__(self, SR, x=0):
"""
Nearly all expressions are created by calling new_Expression_from_*,
but we need to make sure this at least does not leave self._gobj
uninitialized and segfault.
TESTS::
sage: sage.symbolic.expression.Expression(SR)
0
sage: sage.symbolic.expression.Expression(SR, 5)
5
We test subclassing ``Expression``::
sage: from sage.symbolic.expression import Expression
sage: class exp_sub(Expression): pass
sage: f = function('f')
sage: t = f(x)
sage: u = exp_sub(SR, t)
sage: u.operator()
f
"""
self._parent = SR
cdef Expression exp = self.coerce_in(x)
GEx_construct_ex(&self._gobj, exp._gobj)
def __dealloc__(self):
"""
Delete memory occupied by this expression.
"""
GEx_destruct(&self._gobj)
def __getstate__(self):
"""
Return a tuple describing the state of this expression for pickling.
This should return all information that will be required to unpickle
the object. The functionality for unpickling is implemented in
__setstate__().
In order to pickle Expression objects, we return a tuple containing
* 0 - as pickle version number
in case we decide to change the pickle format in the feature
* names of symbols of this expression
* a string representation of self stored in a Pynac archive.
TESTS::
sage: var('x,y,z')
(x, y, z)
sage: t = 2*x*y^z+3
sage: s = dumps(t)
sage: t.__getstate__()
(0,
['x', 'y', 'z'],
...)
"""
cdef GArchive ar
ar.archive_ex(self._gobj, "sage_ex")
ar_str = GArchive_to_str(&ar)
return (0, map(repr, self.variables()), ar_str)
def _dbgprint(self):
r"""
Print pynac debug output to ``stderr``.
EXAMPLES::
sage: (1+x)._dbgprint()
x + 1
"""
self._gobj.dbgprint()
def _dbgprinttree(self):
r"""
Print pynac expression tree debug output to ``stderr``.
EXAMPLES:
The expression tree is composed of Ginac primitives
and functions, organized by the tree, with various
other memory and hash information which will vary::
sage: (1+x+exp(x+1))._dbgprinttree() # not tested
add @0x65e5960, hash=0x4727e01a, flags=0x3, nops=3
x (symbol) @0x6209150, serial=6, hash=0x2057b15e, flags=0xf, domain=0
1 (numeric) @0x3474cf0, hash=0x0, flags=0x7
-----
function exp @0x24835d0, hash=0x765c2165, flags=0xb, nops=1
add @0x65df570, hash=0x420740d2, flags=0xb, nops=2
x (symbol) @0x6209150, serial=6, hash=0x2057b15e, flags=0xf, domain=0
1 (numeric) @0x3474cf0, hash=0x0, flags=0x7
-----
overall_coeff
1 (numeric) @0x65e4df0, hash=0x7fd3, flags=0x7
=====
=====
1 (numeric) @0x3474cf0, hash=0x0, flags=0x7
-----
overall_coeff
1 (numeric) @0x663cc40, hash=0x7fd3, flags=0x7
=====
TESTS:
This test is just to make sure the function is working::
sage: (1+x+exp(x+1))._dbgprinttree()
add @...
x (symbol) ...
1 (numeric) ...
...
overall_coeff
1 (numeric) ...
=====
"""
self._gobj.dbgprinttree();
def __setstate__(self, state):
"""
Initialize the state of the object from data saved in a pickle.
During unpickling __init__ methods of classes are not called, the saved
data is passed to the class via this function instead.
TESTS::
sage: var('x,y,z')
(x, y, z)
sage: t = 2*x*y^z+3
sage: u = loads(dumps(t)) # indirect doctest
sage: u
2*x*y^z + 3
sage: bool(t == u)
True
sage: u.subs(x=z)
2*y^z*z + 3
sage: loads(dumps(x.parent()(2)))
2
"""
# check input
if state[0] != 0 or len(state) != 3:
raise ValueError("unknown state information")
# set parent
self._set_parent(ring.SR)
# get variables
cdef GExList sym_lst
for name in state[1]:
sym_lst.append_sym(\
ex_to_symbol((<Expression>ring.SR.symbol(name))._gobj))
# initialize archive
cdef GArchive ar
GArchive_from_str(&ar, state[2], len(state[2]))
# extract the expression from the archive
GEx_construct_ex(&self._gobj, ar.unarchive_ex(sym_lst, <unsigned>0))
def __copy__(self):
"""
TESTS::
sage: copy(x)
x
"""
return new_Expression_from_GEx(self._parent, self._gobj)
def _repr_(self):
"""
Return string representation of this symbolic expression.
EXAMPLES::
sage: var("x y")
(x, y)
sage: repr(x+y)
'x + y'
TESTS::
# printing of modular number equal to -1 as coefficient
sage: k.<a> = GF(9); k(2)*x
2*x
sage: (x+1)*Mod(6,7)
6*x + 6
#printing rational functions
sage: x/y
x/y
sage: x/2/y
1/2*x/y
sage: .5*x/y
0.500000000000000*x/y
sage: x^(-1)
1/x
sage: x^(-5)
x^(-5)
sage: x^(-y)
x^(-y)
sage: 2*x^(-1)
2/x
sage: i*x
I*x
sage: -x.parent(i)
-I
sage: y + 3*(x^(-1))
y + 3/x
Printing the exp function::
sage: x.parent(1).exp()
e
sage: x.exp()
e^x
Powers::
sage: _ = var('A,B,n'); (A*B)^n
(A*B)^n
sage: (A/B)^n
(A/B)^n
sage: n*x^(n-1)
n*x^(n - 1)
sage: (A*B)^(n+1)
(A*B)^(n + 1)
sage: (A/B)^(n-1)
(A/B)^(n - 1)
sage: n*x^(n+1)
n*x^(n + 1)
sage: n*x^(n-1)
n*x^(n - 1)
sage: n*(A/B)^(n+1)
n*(A/B)^(n + 1)
sage: (n+A/B)^(n+1)
(n + A/B)^(n + 1)
Powers where the base or exponent is a Python object::
sage: (2/3)^x
(2/3)^x
sage: x^CDF(1,2)
x^(1.0 + 2.0*I)
sage: (2/3)^(2/3)
(2/3)^(2/3)
sage: (-x)^(1/4)
(-x)^(1/4)
sage: k.<a> = GF(9)
sage: SR(a+1)^x
(a + 1)^x
Check if :trac:`7876` is fixed::
sage: (1/2-1/2*I )*sqrt(2)
-(1/2*I - 1/2)*sqrt(2)
sage: latex((1/2-1/2*I )*sqrt(2))
-\left(\frac{1}{2} i - \frac{1}{2}\right) \, \sqrt{2}
Check if :trac:`9632` is fixed::
sage: zeta(x) + cos(x)
cos(x) + zeta(x)
sage: psi(1,1/3)*log(3)
log(3)*psi(1, 1/3)
"""
return self._parent._repr_element_(self)
def _ascii_art_(self):
"""
TESTS::
sage: i = var('i')
sage: ascii_art(sum(i^2/pi*x^i, i, 0, oo))
2
x + x
-------------------------------
3 2
- pi*x + 3*pi*x - 3*pi*x + pi
sage: ascii_art(integral(exp(x + x^2)/(x+1), x))
/
|
| 2
| x + x
| e
| ------- dx
| x + 1
|
/
"""
from sympy import pretty, sympify
from sage.misc.ascii_art import AsciiArt
# FIXME:: when *sage* will use at least sympy >= 0.7.2
# we could use a nice splitting with respect of the AsciiArt module.
# from sage.misc.ascii_art import AsciiArt, MAX_LENGTH ## for import
# num_columns = MAX_LENGTH ## option of pretty
try:
s = pretty(sympify(self, evaluate=False), use_unicode=False)
except StandardError:
s = self
return AsciiArt(str(s).splitlines())
def _interface_(self, I):
"""
EXAMPLES::
sage: f = sin(e + 2)
sage: f._interface_(sage.calculus.calculus.maxima)
sin(%e+2)
"""
if is_a_constant(self._gobj):
return self.pyobject()._interface_(I)
return super(Expression, self)._interface_(I)
def _maxima_(self, session=None):
"""
EXAMPLES::
sage: f = sin(e + 2)
sage: f._maxima_()
sin(%e+2)
sage: _.parent() is sage.calculus.calculus.maxima
True
"""
if session is None:
# This chooses the Maxima interface used by calculus
# Maybe not such a great idea because the "default" interface is another one
from sage.calculus.calculus import maxima
return super(Expression, self)._interface_(maxima)
else:
return super(Expression, self)._interface_(session)
def _interface_init_(self, I):
"""
EXAMPLES::
sage: a = (pi + 2).sin()
sage: a._maxima_init_()
'sin((%pi)+(2))'
sage: a = (pi + 2).sin()
sage: a._maple_init_()
'sin((pi)+(2))'
sage: a = (pi + 2).sin()
sage: a._mathematica_init_()
'Sin[(Pi)+(2)]'
sage: f = pi + I*e
sage: f._pari_init_()
'(Pi)+((exp(1))*(I))'
TESTS:
Check if complex numbers are converted to Maxima correctly
:trac:`7557`::
sage: SR(1.5*I)._maxima_init_()
'1.5000000000000000*%i'
sage: SR(CC.0)._maxima_init_()
'1.0000000000000000*%i'
sage: SR(CDF.0)._maxima_init_()
'1.0000000000000000*%i'
"""
from sage.symbolic.expression_conversions import InterfaceInit
return InterfaceInit(I)(self)
def _gap_init_(self):
"""
Convert symbolic object to GAP string.
EXAMPLES::
sage: gap(e + pi^2 + x^3)
x^3 + pi^2 + e
"""
return '"%s"'%repr(self)
def _singular_init_(self):
"""
Conversion of a symbolic object to Singular string.
EXAMPLES::
sage: singular(e + pi^2 + x^3)
x^3 + pi^2 + e
"""
return '"%s"'%repr(self)
def _magma_init_(self, magma):
"""
Return string representation in Magma of this symbolic expression.
Since Magma has no notation of symbolic calculus, this simply
returns something that evaluates in Magma to a a Magma string.
EXAMPLES::
sage: x = var('x')
sage: f = sin(cos(x^2) + log(x))
sage: f._magma_init_(magma)
'"sin(cos(x^2) + log(x))"'
sage: magma(f) # optional - magma
sin(cos(x^2) + log(x))
sage: magma(f).Type() # optional - magma
MonStgElt
"""
return '"%s"'%repr(self)
def _latex_(self):
r"""
Return string representation of this symbolic expression.
TESTS::
sage: var('x,y,z')
(x, y, z)
sage: latex(y + 3*(x^(-1)))
y + \frac{3}{x}
sage: latex(x^(y+z^(1/y)))
x^{y + z^{\left(\frac{1}{y}\right)}}
sage: latex(1/sqrt(x+y))
\frac{1}{\sqrt{x + y}}
sage: latex(sin(x*(z+y)^x))
\sin\left(x {\left(y + z\right)}^{x}\right)
sage: latex(3/2*(x+y)/z/y)
\frac{3 \, {\left(x + y\right)}}{2 \, y z}
sage: latex((2^(x^y)))
2^{\left(x^{y}\right)}
sage: latex(abs(x))
{\left| x \right|}
sage: latex((x*y).conjugate())
\overline{x} \overline{y}
sage: latex(x*(1/(x^2)+sqrt(x^7)))
x {\left(\sqrt{x^{7}} + \frac{1}{x^{2}}\right)}
Check spacing of coefficients of mul expressions (:trac:`3202` and
:trac:`13356`)::
sage: latex(2*3^x)
2 \cdot 3^{x}
sage: latex(1/2/3^x)
\frac{1}{2 \cdot 3^{x}}
sage: latex(1/2*3^x)
\frac{1}{2} \cdot 3^{x}
Powers::
sage: _ = var('A,B,n')
sage: latex((n+A/B)^(n+1))
{\left(n + \frac{A}{B}\right)}^{n + 1}
sage: latex((A*B)^n)
\left(A B\right)^{n}
sage: latex((A*B)^(n-1))
\left(A B\right)^{n - 1}
Powers where the base or exponent is a Python object::
sage: latex((2/3)^x)
\left(\frac{2}{3}\right)^{x}
sage: latex(x^CDF(1,2))
x^{1.0 + 2.0i}
sage: latex((2/3)^(2/3))
\left(\frac{2}{3}\right)^{\frac{2}{3}}
sage: latex((-x)^(1/4))
\left(-x\right)^{\frac{1}{4}}
sage: k.<a> = GF(9)
sage: latex(SR(a+1)^x)
\left(a + 1\right)^{x}
More powers (:trac:`7406`)::
sage: latex((x^pi)^e)
{\left(x^{\pi}\right)}^{e}
sage: latex((x^(pi+1))^e)
{\left(x^{\pi + 1}\right)}^{e}
sage: a,b,c = var('a b c')
sage: latex(a^(b^c))
a^{\left(b^{c}\right)}
sage: latex((a^b)^c)
{\left(a^{b}\right)}^{c}
Separate coefficients to numerator and denominator (:trac:`7363`)::
sage: latex(2/(x+1))
\frac{2}{x + 1}
sage: latex(1/2/(x+1))
\frac{1}{2 \, {\left(x + 1\right)}}
Check if rational function coefficients without a ``numerator()`` method
are printed correctly. :trac:`8491`::
sage: latex(6.5/x)
\frac{6.50000000000000}{x}
sage: latex(Mod(2,7)/x)
\frac{2}{x}
Check if we avoid extra parenthesis in rational functions (:trac:`8688`)::
sage: latex((x+2)/(x^3+1))
\frac{x + 2}{x^{3} + 1}
sage: latex((x+2)*(x+1)/(x^3+1))
\frac{{\left(x + 2\right)} {\left(x + 1\right)}}{x^{3} + 1}
sage: latex((x+2)/(x^3+1)/(x+1))
\frac{x + 2}{{\left(x^{3} + 1\right)} {\left(x + 1\right)}}
Check that the sign is correct (:trac:`9086`)::
sage: latex(-1/x)
-\frac{1}{x}
sage: latex(1/-x)
-\frac{1}{x}
More tests for the sign (:trac:`9314`)::
sage: latex(-2/x)
-\frac{2}{x}
sage: latex(-x/y)
-\frac{x}{y}
sage: latex(-x*z/y)
-\frac{x z}{y}
sage: latex(-x/z/y)
-\frac{x}{y z}
Check if :trac:`9394` is fixed::
sage: var('n')
n
sage: latex( e^(2*I*pi*n*x - 2*I*pi*n) )
e^{\left(2 i \, \pi n x - 2 i \, \pi n\right)}
sage: latex( e^(2*I*pi*n*x - (2*I+1)*pi*n) )
e^{\left(2 i \, \pi n x - \left(2 i + 1\right) \, \pi n\right)}
sage: x+(1-2*I)*y
x - (2*I - 1)*y
sage: latex(x+(1-2*I)*y)
x - \left(2 i - 1\right) \, y
Check if complex coefficients with denominators are displayed
correctly (:trac:`10769`)::
sage: var('a x')
(a, x)
sage: latex(1/2*I/x)
\frac{i}{2 \, x}
sage: ratio = i/2* x^2/a
sage: latex(ratio)
\frac{i \, x^{2}}{2 \, a}
Parenthesis in powers (:trac:`13262`)::
sage: latex(1+x^(2/3)+x^(-2/3))
x^{\frac{2}{3}} + \frac{1}{x^{\frac{2}{3}}} + 1
"""
return self._parent._latex_element_(self)
def _mathml_(self):
"""
Return a MathML representation of this object.
EXAMPLES::
sage: mathml(pi)
<mi>π</mi>
sage: mathml(pi+2)
MATHML version of the string pi + 2
"""
from sage.misc.all import mathml
try:
obj = self.pyobject()
except TypeError:
return mathml(repr(self))
return mathml(obj)
def _integer_(self, ZZ=None):
"""
EXAMPLES::
sage: f = x^3 + 17*x -3
sage: ZZ(f.coefficient(x^3))
1
sage: ZZ(f.coefficient(x))
17
sage: ZZ(f.coefficient(x,0))
-3
sage: type(ZZ(f.coefficient(x,0)))
<type 'sage.rings.integer.Integer'>
Coercion is done if necessary::
sage: f = x^3 + 17/1*x
sage: ZZ(f.coefficient(x))
17
sage: type(ZZ(f.coefficient(x)))
<type 'sage.rings.integer.Integer'>
If the symbolic expression is just a wrapper around an integer,
that very same integer is returned::
sage: n = 17; SR(n)._integer_() is n
True
"""
try:
n = self.pyobject()
except TypeError:
raise TypeError("unable to convert x (=%s) to an integer" % self)
if isinstance(n, sage.rings.integer.Integer):
return n
return sage.rings.integer.Integer(n)
def __int__(self):
"""
EXAMPLES::
sage: int(log(8)/log(2))
3
sage: int(-log(8)/log(2))
-3
sage: int(sin(2)*100)
90
sage: int(-sin(2)*100)
-90
sage: int(SR(3^64)) == 3^64
True
sage: int(SR(10^100)) == 10^100
True
sage: int(SR(10^100-10^-100)) == 10^100 - 1
True
sage: int(sqrt(-3))
Traceback (most recent call last):
...
ValueError: cannot convert sqrt(-3) to int
"""
from sage.functions.all import floor, ceil
try:
rif_self = sage.rings.all.RIF(self)
except TypeError:
raise ValueError("cannot convert %s to int" % self)
if rif_self > 0 or (rif_self.contains_zero() and self > 0):
result = floor(self)
else:
result = ceil(self)
if not isinstance(result, sage.rings.integer.Integer):
raise ValueError("cannot convert %s to int" % self)
else:
return int(result)
def __long__(self):
"""
EXAMPLES::
sage: long(sin(2)*100)
90L
"""
return long(int(self))
def _rational_(self):
"""
EXAMPLES::
sage: f = x^3 + 17/1*x - 3/8
sage: QQ(f.coefficient(x^2))
0
sage: QQ(f.coefficient(x^3))
1
sage: a = QQ(f.coefficient(x)); a
17
sage: type(a)
<type 'sage.rings.rational.Rational'>
sage: QQ(f.coefficient(x,0))
-3/8
If the symbolic expression is just a wrapper around a rational,
that very same rational is returned::
sage: n = 17/1; SR(n)._rational_() is n
True
"""
try:
n = self.pyobject()
except TypeError:
raise TypeError("unable to convert %s to a rational" % self)
if isinstance(n, sage.rings.rational.Rational):
return n
return sage.rings.rational.Rational(n)
cpdef _eval_self(self, R):
"""
Evaluate this expression numerically.
This function is used to convert symbolic expressions to ``RR``,
``CC``, ``float``, ``complex``, ``CIF`` and ``RIF``.
EXAMPLES::
sage: var('x,y,z')
(x, y, z)
sage: sin(x).subs(x=5)._eval_self(RR)
-0.958924274663138
sage: gamma(x).subs(x=I)._eval_self(CC)
-0.154949828301811 - 0.498015668118356*I
sage: x._eval_self(CC)
Traceback (most recent call last):
...
TypeError: Cannot evaluate symbolic expression to a numeric value.
Check if we can compute a real evaluation even if the expression
contains complex coefficients::
sage: RR((I - sqrt(2))*(I+sqrt(2)))
-3.00000000000000
sage: cos(I)._eval_self(RR)
1.54308063481524
sage: float(cos(I))
1.5430806348152437
"""
cdef GEx res
try:
res = self._gobj.evalf(0, {'parent':R})
except TypeError as err:
# try the evaluation again with the complex field
# corresponding to the parent R
if R is float:
R_complex = complex
else:
try:
R_complex = R.complex_field()
except (TypeError, AttributeError):
raise err
res = self._gobj.evalf(0, {'parent':R_complex})
if is_a_numeric(res):
return R(py_object_from_numeric(res))
else:
raise TypeError("Cannot evaluate symbolic expression to a numeric value.")
cpdef _convert(self, kwds):
"""
Convert all the numeric coefficients and constants in this expression
to the given ring `R`. This results in an expression which contains
only variables, and functions whose arguments contain a variable.
EXAMPLES::
sage: f = sqrt(2) * cos(3); f
sqrt(2)*cos(3)