Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/misc/functional.py
4036 views
1
# -*- coding: utf-8 -*-
2
"""
3
Functional notation
4
5
These are functions so that you can write foo(x) instead of x.foo()
6
in certain common cases.
7
8
AUTHORS:
9
10
- William Stein: Initial version
11
12
- David Joyner (2005-12-20): More Examples
13
"""
14
15
#*****************************************************************************
16
# Copyright (C) 2004 William Stein <[email protected]>
17
#
18
# Distributed under the terms of the GNU General Public License (GPL)
19
#
20
# This code is distributed in the hope that it will be useful,
21
# but WITHOUT ANY WARRANTY; without even the implied warranty of
22
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23
# General Public License for more details.
24
#
25
# The full text of the GPL is available at:
26
#
27
# http://www.gnu.org/licenses/
28
#*****************************************************************************
29
30
31
import sage.misc.latex
32
import sage.interfaces.expect
33
import sage.interfaces.mathematica
34
35
36
from sage.rings.complex_double import CDF
37
from sage.rings.real_double import RDF, RealDoubleElement
38
39
import sage.rings.real_mpfr
40
import sage.rings.complex_field
41
import sage.rings.integer
42
43
import __builtin__
44
45
LOG_TEN_TWO_PLUS_EPSILON = 3.321928094887363 # a small overestimate of log(10,2)
46
47
##############################################################################
48
# There are many functions on elements of a ring, which mathematicians
49
# usually write f(x), e.g., it is weird to write x.log() and natural
50
# to write log(x). The functions below allow for the more familiar syntax.
51
##############################################################################
52
def additive_order(x):
53
"""
54
Returns the additive order of `x`.
55
56
EXAMPLES::
57
58
sage: additive_order(5)
59
+Infinity
60
sage: additive_order(Mod(5,11))
61
11
62
sage: additive_order(Mod(4,12))
63
3
64
"""
65
return x.additive_order()
66
67
def base_ring(x):
68
"""
69
Returns the base ring over which x is defined.
70
71
EXAMPLES::
72
73
sage: R = PolynomialRing(GF(7), 'x')
74
sage: base_ring(R)
75
Finite Field of size 7
76
"""
77
return x.base_ring()
78
79
def base_field(x):
80
"""
81
Returns the base field over which x is defined.
82
83
EXAMPLES::
84
85
sage: R = PolynomialRing(GF(7), 'x')
86
sage: base_ring(R)
87
Finite Field of size 7
88
sage: base_field(R)
89
Finite Field of size 7
90
91
This catches base rings which are fields as well, but does
92
not implement a ``base_field`` method for objects which do
93
not have one::
94
95
sage: R.base_field()
96
Traceback (most recent call last):
97
...
98
AttributeError: 'PolynomialRing_dense_mod_p_with_category' object has no attribute 'base_field'
99
"""
100
try:
101
return x.base_field()
102
except AttributeError:
103
try:
104
y = x.base_ring()
105
if is_field(y):
106
return y
107
else:
108
raise AttributeError, "The base ring of %s is not a field"%x
109
except:
110
raise
111
112
def basis(x):
113
"""
114
Returns the fixed basis of x.
115
116
EXAMPLES::
117
118
sage: V = VectorSpace(QQ,3)
119
sage: S = V.subspace([[1,2,0],[2,2,-1]])
120
sage: basis(S)
121
[
122
(1, 0, -1),
123
(0, 1, 1/2)
124
]
125
"""
126
return x.basis()
127
128
def category(x):
129
"""
130
Returns the category of x.
131
132
EXAMPLES::
133
134
sage: V = VectorSpace(QQ,3)
135
sage: category(V)
136
Category of vector spaces over Rational Field
137
"""
138
try:
139
return x.category()
140
except AttributeError:
141
import sage.categories.all
142
return sage.categories.all.Objects()
143
144
def ceil(x):
145
"""
146
Returns the ceiling (least integer) function of x.
147
148
EXAMPLES::
149
150
sage: ceil(3.5)
151
4
152
sage: ceil(7/2)
153
4
154
sage: ceil(-3.5)
155
-3
156
sage: ceil(RIF(1.3,2.3))
157
3.?
158
"""
159
try:
160
return x.ceil()
161
except AttributeError:
162
return sage.rings.all.ceil(x)
163
164
def characteristic_polynomial(x, var='x'):
165
"""
166
Returns the characteristic polynomial of x in the given variable.
167
168
EXAMPLES::
169
170
sage: M = MatrixSpace(QQ,3,3)
171
sage: A = M([1,2,3,4,5,6,7,8,9])
172
sage: charpoly(A)
173
x^3 - 15*x^2 - 18*x
174
sage: charpoly(A, 't')
175
t^3 - 15*t^2 - 18*t
176
177
::
178
179
sage: k.<alpha> = GF(7^10); k
180
Finite Field in alpha of size 7^10
181
sage: alpha.charpoly('T')
182
T^10 + T^6 + T^5 + 4*T^4 + T^3 + 2*T^2 + 3*T + 3
183
sage: characteristic_polynomial(alpha, 'T')
184
T^10 + T^6 + T^5 + 4*T^4 + T^3 + 2*T^2 + 3*T + 3
185
"""
186
try:
187
return x.charpoly(var)
188
except AttributeError:
189
raise NotImplementedError, "computation of charpoly of x (=%s) not implemented"%x
190
191
charpoly = characteristic_polynomial
192
193
194
def coerce(P, x):
195
"""
196
Attempts to coerce x to type P if possible.
197
198
EXAMPLES::
199
200
sage: type(5)
201
<type 'sage.rings.integer.Integer'>
202
sage: type(coerce(QQ,5))
203
<type 'sage.rings.rational.Rational'>
204
"""
205
try:
206
return P._coerce_(x)
207
except AttributeError:
208
return P(x)
209
210
211
def acos(x):
212
"""
213
Returns the arc cosine of x.
214
215
EXAMPLES::
216
217
sage: acos(.5)
218
1.04719755119660
219
sage: acos(sin(pi/3))
220
arccos(1/2*sqrt(3))
221
sage: acos(sin(pi/3)).simplify_full()
222
1/6*pi
223
"""
224
try: return x.acos()
225
except AttributeError: return RDF(x).acos()
226
227
def asin(x):
228
"""
229
Returns the arc sine of x.
230
231
EXAMPLES::
232
233
sage: asin(.5)
234
0.523598775598299
235
sage: asin(sin(pi/3))
236
arcsin(1/2*sqrt(3))
237
sage: asin(sin(pi/3)).simplify_full()
238
1/3*pi
239
"""
240
try: return x.asin()
241
except AttributeError: return RDF(x).asin()
242
243
def atan(x):
244
"""
245
Returns the arc tangent of x.
246
247
EXAMPLES::
248
249
sage: z = atan(3);z
250
arctan(3)
251
sage: n(z)
252
1.24904577239825
253
sage: atan(tan(pi/4))
254
1/4*pi
255
"""
256
try: return x.atan()
257
except AttributeError: return RDF(x).atan()
258
259
## def cuspidal_submodule(x):
260
## return x.cuspidal_submodule()
261
262
## def cuspidal_subspace(x):
263
## return x.cuspidal_subspace()
264
265
def cyclotomic_polynomial(n, var='x'):
266
"""
267
Returns the `n^{th}` cyclotomic polynomial.
268
269
EXAMPLES::
270
271
sage: cyclotomic_polynomial(3)
272
x^2 + x + 1
273
sage: cyclotomic_polynomial(4)
274
x^2 + 1
275
sage: cyclotomic_polynomial(9)
276
x^6 + x^3 + 1
277
sage: cyclotomic_polynomial(10)
278
x^4 - x^3 + x^2 - x + 1
279
sage: cyclotomic_polynomial(11)
280
x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x + 1
281
"""
282
return sage.rings.all.ZZ[var].cyclotomic_polynomial(n)
283
284
def decomposition(x):
285
"""
286
Returns the decomposition of x.
287
288
EXAMPLES::
289
290
sage: M = matrix([[2, 3], [3, 4]])
291
sage: M.decomposition()
292
[
293
(Ambient free module of rank 2 over the principal ideal domain Integer Ring, True)
294
]
295
296
::
297
298
sage: G.<a,b> = DirichletGroup(20)
299
sage: c = a*b
300
sage: d = c.decomposition(); d
301
[Dirichlet character modulo 4 of conductor 4 mapping 3 |--> -1,
302
Dirichlet character modulo 5 of conductor 5 mapping 2 |--> zeta4]
303
sage: d[0].parent()
304
Group of Dirichlet characters of modulus 4 over Cyclotomic Field of order 4 and degree 2
305
"""
306
return x.decomposition()
307
308
def denominator(x):
309
"""
310
Returns the denominator of x.
311
312
EXAMPLES::
313
314
sage: denominator(17/11111)
315
11111
316
sage: R.<x> = PolynomialRing(QQ)
317
sage: F = FractionField(R)
318
sage: r = (x+1)/(x-1)
319
sage: denominator(r)
320
x - 1
321
"""
322
if isinstance(x, (int, long)):
323
return 1
324
return x.denominator()
325
326
def det(x):
327
"""
328
Returns the determinant of x.
329
330
EXAMPLES::
331
332
sage: M = MatrixSpace(QQ,3,3)
333
sage: A = M([1,2,3,4,5,6,7,8,9])
334
sage: det(A)
335
0
336
"""
337
return x.det()
338
339
def dimension(x):
340
"""
341
Returns the dimension of x.
342
343
EXAMPLES::
344
345
sage: V = VectorSpace(QQ,3)
346
sage: S = V.subspace([[1,2,0],[2,2,-1]])
347
sage: dimension(S)
348
2
349
"""
350
return x.dimension()
351
352
dim = dimension
353
354
def discriminant(x):
355
"""
356
Returns the discriminant of x.
357
358
EXAMPLES::
359
360
sage: R.<x> = PolynomialRing(QQ)
361
sage: S = R.quotient(x^29 - 17*x - 1, 'alpha')
362
sage: K = S.number_field()
363
sage: discriminant(K)
364
-15975100446626038280218213241591829458737190477345113376757479850566957249523
365
"""
366
return x.discriminant()
367
368
disc = discriminant
369
370
# This is dangerous since it gets the scoping all wrong ??
371
#import __builtin__
372
#def eval(x):
373
# try:
374
# return x._eval_()
375
# except AttributeError:
376
# return __builtin__.eval(x)
377
378
def eta(x):
379
r"""
380
Returns the value of the eta function at `x`, which must be
381
in the upper half plane.
382
383
The `\eta` function is
384
385
.. math::
386
387
\eta(z) = e^{\pi i z / 12} \prod_{n=1}^{\infty}(1-e^{2\pi inz})
388
389
390
391
EXAMPLES::
392
393
sage: eta(1+I)
394
0.742048775837 + 0.19883137023*I
395
"""
396
try: return x.eta()
397
except AttributeError: return CDF(x).eta()
398
399
def exp(x):
400
"""
401
Returns the value of the exponentiation function at x.
402
403
EXAMPLES::
404
405
sage: exp(3)
406
e^3
407
sage: exp(0)
408
1
409
sage: exp(2.5)
410
12.1824939607035
411
sage: exp(pi*i)
412
-1
413
"""
414
try: return x.exp()
415
except AttributeError: return RDF(x).exp()
416
417
def factor(x, *args, **kwds):
418
"""
419
Returns the (prime) factorization of x.
420
421
EXAMPLES::
422
423
sage: factor(factorial(10))
424
2^8 * 3^4 * 5^2 * 7
425
sage: n = next_prime(10^6); n
426
1000003
427
sage: factor(n)
428
1000003
429
430
Note that this depends on the type of x::
431
432
sage: factor(55)
433
5 * 11
434
sage: factor(x^2+2*x+1)
435
(x + 1)^2
436
sage: factor(55*x^2+110*x+55)
437
55*(x + 1)^2
438
439
"""
440
try: return x.factor(*args, **kwds)
441
except AttributeError: return sage.rings.all.factor(x, *args, **kwds)
442
443
factorization = factor
444
factorisation = factor
445
446
def fcp(x, var='x'):
447
"""
448
Returns the factorization of the characteristic polynomial of x.
449
450
EXAMPLES::
451
452
sage: M = MatrixSpace(QQ,3,3)
453
sage: A = M([1,2,3,4,5,6,7,8,9])
454
sage: fcp(A, 'x')
455
x * (x^2 - 15*x - 18)
456
"""
457
try: return x.fcp(var)
458
except AttributeError: return factor(charpoly(x, var))
459
460
## def floor(x):
461
## try:
462
## return x.floor()
463
## except AttributeError:
464
## return sage.rings.all.floor(x)
465
466
def gen(x):
467
"""
468
Returns the generator of x.
469
470
EXAMPLES::
471
472
sage: R.<x> = QQ[]; R
473
Univariate Polynomial Ring in x over Rational Field
474
sage: gen(R)
475
x
476
sage: gen(GF(7))
477
1
478
sage: A = AbelianGroup(1, [23])
479
sage: gen(A)
480
f
481
"""
482
return x.gen()
483
484
def gens(x):
485
"""
486
Returns the generators of x.
487
488
EXAMPLES::
489
490
sage: R.<x,y> = SR[]
491
sage: R
492
Multivariate Polynomial Ring in x, y over Symbolic Ring
493
sage: gens(R)
494
(x, y)
495
sage: A = AbelianGroup(5, [5,5,7,8,9])
496
sage: gens(A)
497
(f0, f1, f2, f3, f4)
498
"""
499
return x.gens()
500
501
def hecke_operator(x,n):
502
"""
503
Returns the n-th Hecke operator T_n acting on x.
504
505
EXAMPLES::
506
507
sage: M = ModularSymbols(1,12)
508
sage: hecke_operator(M,5)
509
Hecke operator T_5 on Modular Symbols space of dimension 3 for Gamma_0(1) of weight 12 with sign 0 over Rational Field
510
"""
511
return x.hecke_operator(n)
512
513
ideal = sage.rings.ideal.Ideal
514
515
def image(x):
516
"""
517
Returns the image of x.
518
519
EXAMPLES::
520
521
sage: M = MatrixSpace(QQ,3,3)
522
sage: A = M([1,2,3,4,5,6,7,8,9])
523
sage: image(A)
524
Vector space of degree 3 and dimension 2 over Rational Field
525
Basis matrix:
526
[ 1 0 -1]
527
[ 0 1 2]
528
"""
529
return x.image()
530
531
def symbolic_sum(expression, *args, **kwds):
532
r"""
533
Returns the symbolic sum `\sum_{v = a}^b expression` with respect
534
to the variable `v` with endpoints `a` and `b`.
535
536
INPUT:
537
538
- ``expression`` - a symbolic expression
539
540
- ``v`` - a variable or variable name
541
542
- ``a`` - lower endpoint of the sum
543
544
- ``b`` - upper endpoint of the sum
545
546
- ``algorithm`` - (default: 'maxima') one of
547
- 'maxima' - use Maxima (the default)
548
- 'maple' - (optional) use Maple
549
- 'mathematica' - (optional) use Mathematica
550
551
EXAMPLES::
552
553
sage: k, n = var('k,n')
554
sage: sum(k, k, 1, n).factor()
555
1/2*(n + 1)*n
556
557
::
558
559
sage: sum(1/k^4, k, 1, oo)
560
1/90*pi^4
561
562
::
563
564
sage: sum(1/k^5, k, 1, oo)
565
zeta(5)
566
567
A well known binomial identity::
568
569
sage: sum(binomial(n,k), k, 0, n)
570
2^n
571
572
The binomial theorem::
573
574
sage: x, y = var('x, y')
575
sage: sum(binomial(n,k) * x^k * y^(n-k), k, 0, n)
576
(x + y)^n
577
578
::
579
580
sage: sum(k * binomial(n, k), k, 1, n)
581
n*2^(n - 1)
582
583
::
584
585
sage: sum((-1)^k*binomial(n,k), k, 0, n)
586
0
587
588
::
589
590
sage: sum(2^(-k)/(k*(k+1)), k, 1, oo)
591
-log(2) + 1
592
593
Another binomial identity (trac #7952)::
594
595
sage: t,k,i = var('t,k,i')
596
sage: sum(binomial(i+t,t),i,0,k)
597
binomial(k + t + 1, t + 1)
598
599
Summing a hypergeometric term::
600
601
sage: sum(binomial(n, k) * factorial(k) / factorial(n+1+k), k, 0, n)
602
1/2*sqrt(pi)/factorial(n + 1/2)
603
604
We check a well known identity::
605
606
sage: bool(sum(k^3, k, 1, n) == sum(k, k, 1, n)^2)
607
True
608
609
A geometric sum::
610
611
sage: a, q = var('a, q')
612
sage: sum(a*q^k, k, 0, n)
613
(a*q^(n + 1) - a)/(q - 1)
614
615
The geometric series::
616
617
sage: assume(abs(q) < 1)
618
sage: sum(a*q^k, k, 0, oo)
619
-a/(q - 1)
620
621
A divergent geometric series. Don't forget
622
to forget your assumptions::
623
624
sage: forget()
625
sage: assume(q > 1)
626
sage: sum(a*q^k, k, 0, oo)
627
Traceback (most recent call last):
628
...
629
ValueError: Sum is divergent.
630
631
This summation only Mathematica can perform::
632
633
sage: sum(1/(1+k^2), k, -oo, oo, algorithm = 'mathematica') # optional -- requires mathematica
634
pi*coth(pi)
635
636
Use Maple as a backend for summation::
637
638
sage: sum(binomial(n,k)*x^k, k, 0, n, algorithm = 'maple') # optional -- requires maple
639
(x + 1)^n
640
641
Python ints should work as limits of summation (trac #9393)::
642
643
sage: sum(x, x, 1r, 5r)
644
15
645
646
.. note::
647
648
#. Sage can currently only understand a subset of the output of Maxima, Maple and
649
Mathematica, so even if the chosen backend can perform the summation the
650
result might not be convertable into a Sage expression.
651
652
"""
653
if hasattr(expression, 'sum'):
654
return expression.sum(*args, **kwds)
655
elif len(args) <= 1:
656
return sum(expression, *args)
657
else:
658
from sage.symbolic.ring import SR
659
return SR(expression).sum(*args, **kwds)
660
661
def integral(x, *args, **kwds):
662
"""
663
Returns an indefinite or definite integral of an object x.
664
665
First call x.integrate() and if that fails make an object and
666
integrate it using Maxima, maple, etc, as specified by algorithm.
667
668
For symbolic expression calls
669
``sage.calculus.calculus.integral`` - see this function for
670
available options.
671
672
EXAMPLES::
673
674
sage: f = cyclotomic_polynomial(10)
675
sage: integral(f)
676
1/5*x^5 - 1/4*x^4 + 1/3*x^3 - 1/2*x^2 + x
677
678
::
679
680
sage: integral(sin(x),x)
681
-cos(x)
682
683
::
684
685
sage: y = var('y')
686
sage: integral(sin(x),y)
687
y*sin(x)
688
689
::
690
691
sage: integral(sin(x), x, 0, pi/2)
692
1
693
sage: sin(x).integral(x, 0,pi/2)
694
1
695
sage: integral(exp(-x), (x, 1, oo))
696
e^(-1)
697
698
Numerical approximation::
699
700
sage: h = integral(tan(x)/x, (x, 1, pi/3)); h
701
integrate(tan(x)/x, x, 1, 1/3*pi)
702
sage: h.n()
703
0.07571599101...
704
705
Specific algorithm can be used for integration::
706
707
sage: integral(sin(x)^2, x, algorithm='maxima')
708
1/2*x - 1/4*sin(2*x)
709
sage: integral(sin(x)^2, x, algorithm='sympy')
710
-1/2*sin(x)*cos(x) + 1/2*x
711
712
TESTS:
713
714
A symbolic integral from :trac:`11445` that was incorrect in
715
earlier versions of Maxima::
716
717
sage: f = abs(x - 1) + abs(x + 1) - 2*abs(x)
718
sage: integrate(f, (x, -Infinity, Infinity))
719
2
720
721
Another symbolic integral, from :trac:`11238`, that used to return
722
zero incorrectly::
723
724
sage: f = exp(-x) * sinh(sqrt(x))
725
sage: integrate(f, x, 0, Infinity)
726
1/2*sqrt(pi)*e^(1/4)
727
728
"""
729
if hasattr(x, 'integral'):
730
return x.integral(*args, **kwds)
731
else:
732
from sage.symbolic.ring import SR
733
return SR(x).integral(*args, **kwds)
734
735
integrate = integral
736
737
def integral_closure(x):
738
"""
739
Returns the integral closure of x.
740
741
EXAMPLES::
742
743
sage: integral_closure(QQ)
744
Rational Field
745
sage: K.<a> = QuadraticField(5)
746
sage: O2 = K.order(2*a); O2
747
Order in Number Field in a with defining polynomial x^2 - 5
748
sage: integral_closure(O2)
749
Maximal Order in Number Field in a with defining polynomial x^2 - 5
750
"""
751
return x.integral_closure()
752
753
def interval(a, b):
754
r"""
755
Integers between a and b *inclusive* (a and b integers).
756
757
EXAMPLES::
758
759
sage: I = interval(1,3)
760
sage: 2 in I
761
True
762
sage: 1 in I
763
True
764
sage: 4 in I
765
False
766
"""
767
return range(a,b+1)
768
769
def xinterval(a, b):
770
r"""
771
Iterator over the integers between a and b, *inclusive*.
772
773
EXAMPLES::
774
775
sage: I = xinterval(2,5); I
776
xrange(2, 6)
777
sage: 5 in I
778
True
779
sage: 6 in I
780
False
781
"""
782
return xrange(a, b+1)
783
784
def is_commutative(x):
785
"""
786
Returns whether or not x is commutative.
787
788
EXAMPLES::
789
790
sage: R = PolynomialRing(QQ, 'x')
791
sage: is_commutative(R)
792
True
793
"""
794
return x.is_commutative()
795
796
def is_even(x):
797
"""
798
Returns whether or not an integer x is even, e.g., divisible by 2.
799
800
EXAMPLES::
801
802
sage: is_even(-1)
803
False
804
sage: is_even(4)
805
True
806
sage: is_even(-2)
807
True
808
"""
809
try: return x.is_even()
810
except AttributeError: return x%2==0
811
812
def is_integrally_closed(x):
813
"""
814
Returns whether x is integrally closed.
815
816
EXAMPLES::
817
818
sage: is_integrally_closed(QQ)
819
True
820
sage: K.<a> = NumberField(x^2 + 189*x + 394)
821
sage: R = K.order(2*a)
822
sage: is_integrally_closed(R)
823
False
824
"""
825
return x.is_integrally_closed()
826
827
def is_field(x):
828
"""
829
Returns whether or not x is a field.
830
831
EXAMPLES::
832
833
sage: R = PolynomialRing(QQ, 'x')
834
sage: F = FractionField(R)
835
sage: is_field(F)
836
True
837
"""
838
return x.is_field()
839
840
def is_noetherian(x):
841
"""
842
Returns whether or not x is a Noetherian
843
object (has ascending chain condition).
844
845
EXAMPLES::
846
847
sage: from sage.misc.functional import is_noetherian
848
sage: is_noetherian(ZZ)
849
True
850
sage: is_noetherian(QQ)
851
True
852
sage: A = SteenrodAlgebra(3)
853
sage: is_noetherian(A)
854
False
855
"""
856
857
return x.is_noetherian()
858
859
def is_odd(x):
860
"""
861
Returns whether or not x is odd. This is by definition the
862
complement of is_even.
863
864
EXAMPLES::
865
866
sage: is_odd(-2)
867
False
868
sage: is_odd(-3)
869
True
870
sage: is_odd(0)
871
False
872
sage: is_odd(1)
873
True
874
"""
875
return not is_even(x)
876
877
## def j_invariant(x):
878
## """
879
## Return the j_invariant of x.
880
881
## EXAMPLES:
882
## sage: E = EllipticCurve([0, -1, 1, -10, -20])
883
## sage: E
884
## Elliptic Curve defined by y^2 + y = x^3 - x^2 - 10*x - 20 over Rational Field
885
## sage: j_invariant(E)
886
## -122023936/161051
887
## """
888
## return x.j_invariant()
889
890
def kernel(x):
891
"""
892
Returns the left kernel of x.
893
894
EXAMPLES::
895
896
sage: M = MatrixSpace(QQ,3,2)
897
sage: A = M([1,2,3,4,5,6])
898
sage: kernel(A)
899
Vector space of degree 3 and dimension 1 over Rational Field
900
Basis matrix:
901
[ 1 -2 1]
902
sage: kernel(A.transpose())
903
Vector space of degree 2 and dimension 0 over Rational Field
904
Basis matrix:
905
[]
906
907
Here are two corner cases:
908
sage: M=MatrixSpace(QQ,0,3)
909
sage: A=M([])
910
sage: kernel(A)
911
Vector space of degree 0 and dimension 0 over Rational Field
912
Basis matrix:
913
[]
914
sage: kernel(A.transpose()).basis()
915
[
916
(1, 0, 0),
917
(0, 1, 0),
918
(0, 0, 1)
919
]
920
"""
921
return x.kernel()
922
923
def krull_dimension(x):
924
"""
925
Returns the Krull dimension of x.
926
927
EXAMPLES::
928
929
sage: krull_dimension(QQ)
930
0
931
sage: krull_dimension(ZZ)
932
1
933
sage: krull_dimension(ZZ[sqrt(5)])
934
1
935
sage: U.<x,y,z> = PolynomialRing(ZZ,3); U
936
Multivariate Polynomial Ring in x, y, z over Integer Ring
937
sage: U.krull_dimension()
938
4
939
"""
940
return x.krull_dimension()
941
942
def lift(x):
943
"""
944
Lift an object of a quotient ring `R/I` to `R`.
945
946
EXAMPLES: We lift an integer modulo `3`.
947
948
::
949
950
sage: Mod(2,3).lift()
951
2
952
953
We lift an element of a quotient polynomial ring.
954
955
::
956
957
sage: R.<x> = QQ['x']
958
sage: S.<xmod> = R.quo(x^2 + 1)
959
sage: lift(xmod-7)
960
x - 7
961
"""
962
try:
963
return x.lift()
964
except AttributeError:
965
raise ArithmeticError, "no lift defined."
966
967
def log(x,b=None):
968
r"""
969
Returns the log of x to the base b. The default base is e.
970
971
INPUT:
972
973
974
- ``x`` - number
975
976
- ``b`` - base (default: None, which means natural
977
log)
978
979
980
OUTPUT: number
981
982
.. note::
983
984
In Magma, the order of arguments is reversed from in Sage,
985
i.e., the base is given first. We use the opposite ordering, so
986
the base can be viewed as an optional second argument.
987
988
EXAMPLES::
989
990
sage: log(e^2)
991
2
992
sage: log(16,2)
993
4
994
sage: log(3.)
995
1.09861228866811
996
"""
997
if b is None:
998
if hasattr(x, 'log'):
999
return x.log()
1000
return RDF(x)._log_base(1)
1001
else:
1002
if hasattr(x, 'log'):
1003
return x.log(b)
1004
return RDF(x).log(b)
1005
1006
def minimal_polynomial(x, var='x'):
1007
"""
1008
Returns the minimal polynomial of x.
1009
1010
EXAMPLES::
1011
1012
sage: a = matrix(ZZ, 2, [1..4])
1013
sage: minpoly(a)
1014
x^2 - 5*x - 2
1015
sage: minpoly(a,'t')
1016
t^2 - 5*t - 2
1017
sage: minimal_polynomial(a)
1018
x^2 - 5*x - 2
1019
sage: minimal_polynomial(a,'theta')
1020
theta^2 - 5*theta - 2
1021
"""
1022
try:
1023
return x.minpoly(var=var)
1024
except AttributeError:
1025
return x.minimal_polynomial(var=var)
1026
1027
minpoly = minimal_polynomial
1028
1029
1030
def multiplicative_order(x):
1031
r"""
1032
Returns the multiplicative order of self, if self is a unit, or
1033
raise ``ArithmeticError`` otherwise.
1034
1035
EXAMPLES::
1036
1037
sage: a = mod(5,11)
1038
sage: multiplicative_order(a)
1039
5
1040
sage: multiplicative_order(mod(2,11))
1041
10
1042
sage: multiplicative_order(mod(2,12))
1043
Traceback (most recent call last):
1044
...
1045
ArithmeticError: multiplicative order of 2 not defined since it is not a unit modulo 12
1046
"""
1047
return x.multiplicative_order()
1048
1049
## def new_submodule(x):
1050
## return x.new_submodule()
1051
1052
## def new_subspace(x):
1053
## return x.new_subspace()
1054
1055
def ngens(x):
1056
"""
1057
Returns the number of generators of x.
1058
1059
EXAMPLES::
1060
1061
sage: R.<x,y> = SR[]; R
1062
Multivariate Polynomial Ring in x, y over Symbolic Ring
1063
sage: ngens(R)
1064
2
1065
sage: A = AbelianGroup(5, [5,5,7,8,9])
1066
sage: ngens(A)
1067
5
1068
sage: ngens(ZZ)
1069
1
1070
"""
1071
return x.ngens()
1072
1073
def norm(x):
1074
r"""
1075
Returns the norm of ``x``.
1076
1077
For matrices and vectors, this returns the L2-norm. The L2-norm of a
1078
vector `\textbf{v} = (v_1, v_2, \dots, v_n)`, also called the Euclidean
1079
norm, is defined as
1080
1081
.. MATH::
1082
1083
|\textbf{v}|
1084
=
1085
\sqrt{\sum_{i=1}^n |v_i|^2}
1086
1087
where `|v_i|` is the complex modulus of `v_i`. The Euclidean norm is often
1088
used for determining the distance between two points in two- or
1089
three-dimensional space.
1090
1091
For complex numbers, the function returns the field norm. If
1092
`c = a + bi` is a complex number, then the norm of `c` is defined as the
1093
product of `c` and its complex conjugate
1094
1095
.. MATH::
1096
1097
\text{norm}(c)
1098
=
1099
\text{norm}(a + bi)
1100
=
1101
c \cdot \overline{c}
1102
=
1103
a^2 + b^2.
1104
1105
The norm of a complex number is different from its absolute value.
1106
The absolute value of a complex number is defined to be the square
1107
root of its norm. A typical use of the complex norm is in the
1108
integral domain `\ZZ[i]` of Gaussian integers, where the norm of
1109
each Gaussian integer `c = a + bi` is defined as its complex norm.
1110
1111
.. SEEALSO::
1112
1113
- :meth:`sage.matrix.matrix2.Matrix.norm`
1114
1115
- :meth:`sage.modules.free_module_element.FreeModuleElement.norm`
1116
1117
- :meth:`sage.rings.complex_double.ComplexDoubleElement.norm`
1118
1119
- :meth:`sage.rings.complex_number.ComplexNumber.norm`
1120
1121
- :meth:`sage.symbolic.expression.Expression.norm`
1122
1123
EXAMPLES:
1124
1125
The norm of vectors::
1126
1127
sage: z = 1 + 2*I
1128
sage: norm(vector([z]))
1129
sqrt(5)
1130
sage: v = vector([-1,2,3])
1131
sage: norm(v)
1132
sqrt(14)
1133
sage: _ = var("a b c d")
1134
sage: v = vector([a, b, c, d])
1135
sage: norm(v)
1136
sqrt(abs(a)^2 + abs(b)^2 + abs(c)^2 + abs(d)^2)
1137
1138
The norm of matrices::
1139
1140
sage: z = 1 + 2*I
1141
sage: norm(matrix([[z]]))
1142
2.2360679775
1143
sage: M = matrix(ZZ, [[1,2,4,3], [-1,0,3,-10]])
1144
sage: norm(M)
1145
10.6903311292
1146
sage: norm(CDF(z))
1147
5.0
1148
sage: norm(CC(z))
1149
5.00000000000000
1150
1151
The norm of complex numbers::
1152
1153
sage: z = 2 - 3*I
1154
sage: norm(z)
1155
13
1156
sage: a = randint(-10^10, 100^10)
1157
sage: b = randint(-10^10, 100^10)
1158
sage: z = a + b*I
1159
sage: bool(norm(z) == a^2 + b^2)
1160
True
1161
1162
The complex norm of symbolic expressions::
1163
1164
sage: a, b, c = var("a, b, c")
1165
sage: assume((a, 'real'), (b, 'real'), (c, 'real'))
1166
sage: z = a + b*I
1167
sage: bool(norm(z).simplify() == a^2 + b^2)
1168
True
1169
sage: norm(a + b).simplify()
1170
a^2 + 2*a*b + b^2
1171
sage: v = vector([a, b, c])
1172
sage: bool(norm(v).simplify() == sqrt(a^2 + b^2 + c^2))
1173
True
1174
sage: forget()
1175
"""
1176
return x.norm()
1177
1178
def numerator(x):
1179
"""
1180
Returns the numerator of x.
1181
1182
EXAMPLES::
1183
1184
sage: R.<x> = PolynomialRing(QQ)
1185
sage: F = FractionField(R)
1186
sage: r = (x+1)/(x-1)
1187
sage: numerator(r)
1188
x + 1
1189
sage: numerator(17/11111)
1190
17
1191
"""
1192
if isinstance(x, (int, long)):
1193
return x
1194
return x.numerator()
1195
1196
# Following is the top-level numerical_approx function.
1197
# Implement a ._numerical_approx(prec, digits) method for your
1198
# objects to enable the three top-level functions and three methods
1199
1200
def numerical_approx(x, prec=None, digits=None):
1201
r"""
1202
Returns a numerical approximation of an object ``x`` with at
1203
least ``prec`` bits (or decimal ``digits``) of precision.
1204
1205
.. note::
1206
1207
Both upper case ``N`` and lower case ``n`` are aliases for
1208
:func:`numerical_approx`, and all three may be used as
1209
methods.
1210
1211
INPUT:
1212
1213
- ``x`` - an object that has a numerical_approx
1214
method, or can be coerced into a real or complex field
1215
- ``prec (optional)`` - an integer (bits of
1216
precision)
1217
- ``digits (optional)`` - an integer (digits of
1218
precision)
1219
1220
If neither the ``prec`` or ``digits`` are specified,
1221
the default is 53 bits of precision. If both are
1222
specified, then ``prec`` is used.
1223
1224
EXAMPLES::
1225
1226
sage: numerical_approx(pi, 10)
1227
3.1
1228
sage: numerical_approx(pi, digits=10)
1229
3.141592654
1230
sage: numerical_approx(pi^2 + e, digits=20)
1231
12.587886229548403854
1232
sage: n(pi^2 + e)
1233
12.5878862295484
1234
sage: N(pi^2 + e)
1235
12.5878862295484
1236
sage: n(pi^2 + e, digits=50)
1237
12.587886229548403854194778471228813633070946500941
1238
sage: a = CC(-5).n(prec=100)
1239
sage: b = ComplexField(100)(-5)
1240
sage: a == b
1241
True
1242
sage: type(a) == type(b)
1243
True
1244
sage: numerical_approx(9)
1245
9.00000000000000
1246
1247
You can also usually use method notation. ::
1248
1249
sage: (pi^2 + e).n()
1250
12.5878862295484
1251
sage: (pi^2 + e).N()
1252
12.5878862295484
1253
sage: (pi^2 + e).numerical_approx()
1254
12.5878862295484
1255
1256
Vectors and matrices may also have their entries approximated. ::
1257
1258
sage: v = vector(RDF, [1,2,3])
1259
sage: v.n()
1260
(1.00000000000000, 2.00000000000000, 3.00000000000000)
1261
1262
sage: v = vector(CDF, [1,2,3])
1263
sage: v.n()
1264
(1.00000000000000, 2.00000000000000, 3.00000000000000)
1265
sage: _.parent()
1266
Vector space of dimension 3 over Complex Field with 53 bits of precision
1267
sage: v.n(prec=75)
1268
(1.000000000000000000000, 2.000000000000000000000, 3.000000000000000000000)
1269
1270
sage: u = vector(QQ, [1/2, 1/3, 1/4])
1271
sage: n(u, prec=15)
1272
(0.5000, 0.3333, 0.2500)
1273
sage: n(u, digits=5)
1274
(0.50000, 0.33333, 0.25000)
1275
1276
sage: v = vector(QQ, [1/2, 0, 0, 1/3, 0, 0, 0, 1/4], sparse=True)
1277
sage: u = v.numerical_approx(digits=4)
1278
sage: u.is_sparse()
1279
True
1280
sage: u
1281
(0.5000, 0.0000, 0.0000, 0.3333, 0.0000, 0.0000, 0.0000, 0.2500)
1282
1283
sage: A = matrix(QQ, 2, 3, range(6))
1284
sage: A.n()
1285
[0.000000000000000 1.00000000000000 2.00000000000000]
1286
[ 3.00000000000000 4.00000000000000 5.00000000000000]
1287
1288
sage: B = matrix(Integers(12), 3, 8, srange(24))
1289
sage: N(B, digits=2)
1290
[0.00 1.0 2.0 3.0 4.0 5.0 6.0 7.0]
1291
[ 8.0 9.0 10. 11. 0.00 1.0 2.0 3.0]
1292
[ 4.0 5.0 6.0 7.0 8.0 9.0 10. 11.]
1293
1294
TESTS::
1295
1296
sage: numerical_approx(I)
1297
1.00000000000000*I
1298
sage: x = QQ['x'].gen()
1299
sage: F.<k> = NumberField(x^2+2, embedding=sqrt(CC(2))*CC.0)
1300
sage: numerical_approx(k)
1301
1.41421356237309*I
1302
1303
sage: type(numerical_approx(CC(1/2)))
1304
<type 'sage.rings.complex_number.ComplexNumber'>
1305
1306
The following tests :trac:`10761`, in which ``n()`` would break when
1307
called on complex-valued algebraic numbers. ::
1308
1309
sage: E = matrix(3, [3,1,6,5,2,9,7,3,13]).eigenvalues(); E
1310
[18.16815365088822?, -0.08407682544410650? - 0.2190261484802906?*I, -0.08407682544410650? + 0.2190261484802906?*I]
1311
sage: E[1].parent()
1312
Algebraic Field
1313
sage: [a.n() for a in E]
1314
[18.1681536508882, -0.0840768254441065 - 0.219026148480291*I, -0.0840768254441065 + 0.219026148480291*I]
1315
1316
Make sure we've rounded up log(10,2) enough to guarantee
1317
sufficient precision (trac #10164)::
1318
1319
sage: ks = 4*10**5, 10**6
1320
sage: check_str_length = lambda k: len(str(numerical_approx(1+10**-k,digits=k+1)))-1 >= k+1
1321
sage: check_precision = lambda k: numerical_approx(1+10**-k,digits=k+1)-1 > 0
1322
sage: all(check_str_length(k) and check_precision(k) for k in ks)
1323
True
1324
1325
Testing we have sufficient precision for the golden ratio (trac #12163), note
1326
that the decimal point adds 1 to the string length:
1327
1328
sage: len(str(n(golden_ratio, digits=5000)))
1329
5001
1330
sage: len(str(n(golden_ratio, digits=5000000)))
1331
5000001
1332
1333
"""
1334
if prec is None:
1335
if digits is None:
1336
prec = 53
1337
else:
1338
prec = int((digits+1) * LOG_TEN_TWO_PLUS_EPSILON) + 1
1339
try:
1340
return x._numerical_approx(prec)
1341
except AttributeError:
1342
from sage.rings.complex_double import is_ComplexDoubleElement
1343
from sage.rings.complex_number import is_ComplexNumber
1344
if not (is_ComplexNumber(x) or is_ComplexDoubleElement(x)):
1345
try:
1346
return sage.rings.real_mpfr.RealField(prec)(x)
1347
# Trac 10761: now catches ValueErrors as well as TypeErrors
1348
except (TypeError, ValueError):
1349
pass
1350
return sage.rings.complex_field.ComplexField(prec)(x)
1351
1352
n = numerical_approx
1353
N = numerical_approx
1354
1355
def objgens(x):
1356
"""
1357
EXAMPLES::
1358
1359
sage: R, x = objgens(PolynomialRing(QQ,3, 'x'))
1360
sage: R
1361
Multivariate Polynomial Ring in x0, x1, x2 over Rational Field
1362
sage: x
1363
(x0, x1, x2)
1364
"""
1365
return x.objgens()
1366
1367
def objgen(x):
1368
"""
1369
EXAMPLES::
1370
1371
sage: R, x = objgen(FractionField(QQ['x']))
1372
sage: R
1373
Fraction Field of Univariate Polynomial Ring in x over Rational Field
1374
sage: x
1375
x
1376
"""
1377
return x.objgen()
1378
1379
def one(R):
1380
"""
1381
Returns the one element of the ring R.
1382
1383
EXAMPLES::
1384
1385
sage: R.<x> = PolynomialRing(QQ)
1386
sage: one(R)*x == x
1387
True
1388
sage: one(R) in R
1389
True
1390
"""
1391
return R(1)
1392
1393
def order(x):
1394
"""
1395
Returns the order of x. If x is a ring or module element, this is
1396
the additive order of x.
1397
1398
EXAMPLES::
1399
1400
sage: C = CyclicPermutationGroup(10)
1401
sage: order(C)
1402
10
1403
sage: F = GF(7)
1404
sage: order(F)
1405
7
1406
"""
1407
return x.order()
1408
1409
def rank(x):
1410
"""
1411
Returns the rank of x.
1412
1413
EXAMPLES: We compute the rank of a matrix::
1414
1415
sage: M = MatrixSpace(QQ,3,3)
1416
sage: A = M([1,2,3,4,5,6,7,8,9])
1417
sage: rank(A)
1418
2
1419
1420
We compute the rank of an elliptic curve::
1421
1422
sage: E = EllipticCurve([0,0,1,-1,0])
1423
sage: rank(E)
1424
1
1425
"""
1426
return x.rank()
1427
1428
def regulator(x):
1429
"""
1430
Returns the regulator of x.
1431
1432
EXAMPLES::
1433
1434
sage: regulator(NumberField(x^2-2, 'a'))
1435
0.881373587019543
1436
sage: regulator(EllipticCurve('11a'))
1437
1.00000000000000
1438
"""
1439
return x.regulator()
1440
1441
def round(x, ndigits=0):
1442
"""
1443
round(number[, ndigits]) - double-precision real number
1444
1445
Round a number to a given precision in decimal digits (default 0
1446
digits). If no precision is specified this just calls the element's
1447
.round() method.
1448
1449
EXAMPLES::
1450
1451
sage: round(sqrt(2),2)
1452
1.41
1453
sage: q = round(sqrt(2),5); q
1454
1.41421
1455
sage: type(q)
1456
<type 'sage.rings.real_double.RealDoubleElement'>
1457
sage: q = round(sqrt(2)); q
1458
1
1459
sage: type(q)
1460
<type 'sage.rings.integer.Integer'>
1461
sage: round(pi)
1462
3
1463
sage: b = 5.4999999999999999
1464
sage: round(b)
1465
5
1466
1467
1468
Since we use floating-point with a limited range, some roundings can't
1469
be performed::
1470
1471
sage: round(sqrt(Integer('1'*1000)),2)
1472
+infinity
1473
1474
IMPLEMENTATION: If ndigits is specified, it calls Python's builtin
1475
round function, and converts the result to a real double field
1476
element. Otherwise, it tries the argument's .round() method; if
1477
that fails, it reverts to the builtin round function, converted to
1478
a real double field element.
1479
1480
.. note::
1481
1482
This is currently slower than the builtin round function, since
1483
it does more work - i.e., allocating an RDF element and
1484
initializing it. To access the builtin version do
1485
``import __builtin__; __builtin__.round``.
1486
"""
1487
try:
1488
if ndigits:
1489
return RealDoubleElement(__builtin__.round(x, ndigits))
1490
else:
1491
try:
1492
return x.round()
1493
except AttributeError:
1494
return RealDoubleElement(__builtin__.round(x, 0))
1495
except ArithmeticError:
1496
if not isinstance(x, RealDoubleElement):
1497
return round(RDF(x), ndigits)
1498
else:
1499
raise
1500
1501
def quotient(x, y, *args, **kwds):
1502
"""
1503
Returns the quotient object x/y, e.g., a quotient of numbers or of a
1504
polynomial ring x by the ideal generated by y, etc.
1505
1506
EXAMPLES::
1507
1508
sage: quotient(5,6)
1509
5/6
1510
sage: quotient(5.,6.)
1511
0.833333333333333
1512
sage: R.<x> = ZZ[]; R
1513
Univariate Polynomial Ring in x over Integer Ring
1514
sage: I = Ideal(R, x^2+1)
1515
sage: quotient(R, I)
1516
Univariate Quotient Polynomial Ring in xbar over Integer Ring with modulus x^2 + 1
1517
"""
1518
try:
1519
return x.quotient(y, *args, **kwds)
1520
except AttributeError:
1521
return x/y
1522
1523
quo = quotient
1524
1525
def show(x, *args, **kwds):
1526
r"""
1527
Show a graphics object x.
1528
1529
For additional ways to show objects in the notebook, look
1530
at the methods on the html object. For example,
1531
html.table will produce an HTML table from a nested
1532
list.
1533
1534
1535
OPTIONAL INPUT:
1536
1537
1538
- ``filename`` - (default: None) string
1539
1540
1541
SOME OF THESE MAY APPLY:
1542
1543
- ``dpi`` - dots per inch
1544
1545
- ``figsize``- [width, height] (same for square aspect)
1546
1547
- ``axes`` - (default: True)
1548
1549
- ``fontsize`` - positive integer
1550
1551
- ``frame`` - (default: False) draw a MATLAB-like frame around the
1552
image
1553
1554
EXAMPLES::
1555
1556
sage: show(graphs(3))
1557
sage: show(list(graphs(3)))
1558
"""
1559
if not isinstance(x, (sage.interfaces.expect.Expect, sage.interfaces.expect.ExpectElement)):
1560
try:
1561
return x.show(*args, **kwds)
1562
except AttributeError:
1563
pass
1564
if isinstance(x, sage.interfaces.mathematica.MathematicaElement):
1565
return x.show(*args, **kwds)
1566
1567
import types
1568
if isinstance(x, types.GeneratorType):
1569
x = list(x)
1570
if isinstance(x, list):
1571
if len(x) > 0:
1572
from sage.graphs.graph import GenericGraph
1573
if isinstance(x[0], GenericGraph):
1574
import sage.graphs.graph_list as graphs_list
1575
graphs_list.show_graphs(x)
1576
return
1577
_do_show(x)
1578
1579
def _do_show(x):
1580
if sage.plot.plot.DOCTEST_MODE:
1581
return sage.misc.latex.latex(x)
1582
from latex import view
1583
view(x, mode='display')
1584
#raise AttributeError, "object %s does not support show."%(x, )
1585
1586
def sqrt(x):
1587
"""
1588
Returns a square root of x.
1589
1590
This function (``numerical_sqrt``) is deprecated. Use ``sqrt(x,
1591
prec=n)`` instead.
1592
1593
EXAMPLES::
1594
1595
sage: numerical_sqrt(10.1)
1596
doctest:1: DeprecationWarning: numerical_sqrt is deprecated, use sqrt(x, prec=n) instead
1597
3.17804971641414
1598
sage: numerical_sqrt(9)
1599
3
1600
"""
1601
from sage.misc.misc import deprecation
1602
deprecation("numerical_sqrt is deprecated, use sqrt(x, prec=n) instead")
1603
try: return x.sqrt()
1604
except (AttributeError, ValueError):
1605
try:
1606
return RDF(x).sqrt()
1607
except TypeError:
1608
return CDF(x).sqrt()
1609
1610
def isqrt(x):
1611
"""
1612
Returns an integer square root, i.e., the floor of a square root.
1613
1614
EXAMPLES::
1615
1616
sage: isqrt(10)
1617
3
1618
sage: isqrt(10r)
1619
3
1620
"""
1621
try:
1622
return x.isqrt()
1623
except AttributeError:
1624
from sage.functions.all import floor
1625
n = sage.rings.integer.Integer(floor(x))
1626
return n.isqrt()
1627
1628
def squarefree_part(x):
1629
"""
1630
Returns the square free part of `x`, i.e., a divisor
1631
`z` such that `x = z y^2`, for a perfect square
1632
`y^2`.
1633
1634
EXAMPLES::
1635
1636
sage: squarefree_part(100)
1637
1
1638
sage: squarefree_part(12)
1639
3
1640
sage: squarefree_part(10)
1641
10
1642
sage: squarefree_part(216r) # see #8976
1643
6
1644
1645
::
1646
1647
sage: x = QQ['x'].0
1648
sage: S = squarefree_part(-9*x*(x-6)^7*(x-3)^2); S
1649
-9*x^2 + 54*x
1650
sage: S.factor()
1651
(-9) * (x - 6) * x
1652
1653
::
1654
1655
sage: f = (x^3 + x + 1)^3*(x-1); f
1656
x^10 - x^9 + 3*x^8 + 3*x^5 - 2*x^4 - x^3 - 2*x - 1
1657
sage: g = squarefree_part(f); g
1658
x^4 - x^3 + x^2 - 1
1659
sage: g.factor()
1660
(x - 1) * (x^3 + x + 1)
1661
"""
1662
try:
1663
return x.squarefree_part()
1664
except AttributeError:
1665
pass
1666
F = factor(x)
1667
n = parent(x)(1)
1668
for p, e in F:
1669
if e%2 != 0:
1670
n *= p
1671
return n * F.unit()
1672
1673
## def square_root(x):
1674
## """
1675
## Return a square root of x with the same parent as x, if possible,
1676
## otherwise raise a ValueError.
1677
## EXAMPLES:
1678
## sage: square_root(9)
1679
## 3
1680
## sage: square_root(100)
1681
## 10
1682
## """
1683
## try:
1684
## return x.square_root()
1685
## except AttributeError:
1686
## raise NotImplementedError
1687
1688
def transpose(x):
1689
"""
1690
Returns the transpose of x.
1691
1692
EXAMPLES::
1693
1694
sage: M = MatrixSpace(QQ,3,3)
1695
sage: A = M([1,2,3,4,5,6,7,8,9])
1696
sage: transpose(A)
1697
[1 4 7]
1698
[2 5 8]
1699
[3 6 9]
1700
"""
1701
return x.transpose()
1702
1703
## def vector(x, R):
1704
## r"""
1705
## Return the \sage vector over $R$ obtained from x, if possible.
1706
## """
1707
## try:
1708
## return x._vector_(R)
1709
## except AttributeError:
1710
## import sage.modules.free_module_element
1711
## return sage.modules.free_module_element.Vector(x, R)
1712
1713
def zero(R):
1714
"""
1715
Returns the zero element of the ring R.
1716
1717
EXAMPLES::
1718
1719
sage: R.<x> = PolynomialRing(QQ)
1720
sage: zero(R) in R
1721
True
1722
sage: zero(R)*x == zero(R)
1723
True
1724
"""
1725
return R(0)
1726
1727
1728
1729
#################################################################
1730
# Generic parent
1731
#################################################################
1732
def parent(x):
1733
"""
1734
Returns x.parent() if defined, or type(x) if not.
1735
1736
EXAMPLE::
1737
1738
sage: Z = parent(int(5))
1739
sage: Z(17)
1740
17
1741
sage: Z
1742
<type 'int'>
1743
"""
1744
try:
1745
return x.parent()
1746
except AttributeError:
1747
return type(x)
1748
1749
1750