Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/symbolic/pynac.pyx
4102 views
1
###############################################################################
2
# Sage: Open Source Mathematical Software
3
# Copyright (C) 2008 William Stein <[email protected]>
4
# Copyright (C) 2008 Burcin Erocal <[email protected]>
5
# Distributed under the terms of the GNU General Public License (GPL),
6
# version 2 or any later version. The full text of the GPL is available at:
7
# http://www.gnu.org/licenses/
8
###############################################################################
9
10
cdef extern from "pynac_cc.h":
11
long double sage_logl(long double)
12
long double sage_sqrtl(long double)
13
long double sage_tgammal(long double)
14
long double sage_lgammal(long double)
15
16
include "../ext/cdefs.pxi"
17
include "../ext/stdsage.pxi"
18
19
from sage.libs.ginac cimport *
20
21
# for complex log and log gamma
22
include "../gsl/gsl_complex.pxi"
23
include "../gsl/gsl_sf_result.pxi"
24
include "../gsl/gsl_gamma.pxi"
25
26
27
from sage.structure.element import Element
28
from sage.rings.integer_ring import ZZ
29
from sage.rings.integer cimport Integer
30
from sage.rings.rational cimport Rational
31
from sage.rings.real_mpfr import RR, RealField
32
from sage.rings.complex_field import ComplexField
33
from sage.rings.all import CC
34
35
from sage.symbolic.expression cimport Expression, new_Expression_from_GEx
36
from sage.symbolic.function import get_sfunction_from_serial
37
from sage.symbolic.function cimport Function, parent_c
38
from sage.symbolic.constants_c cimport PynacConstant
39
40
import ring
41
42
from sage.rings.integer cimport Integer
43
44
import math
45
from sage.libs.mpmath import utils as mpmath_utils
46
47
#################################################################
48
# Symbolic function helpers
49
#################################################################
50
51
52
cdef public object ex_to_pyExpression(GEx juice):
53
"""
54
Convert given GiNaC::ex object to a python Expression instance.
55
56
Used to pass parameters to custom power and series functions.
57
"""
58
cdef Expression nex
59
nex = <Expression>PY_NEW(Expression)
60
GEx_construct_ex(&nex._gobj, juice)
61
nex._parent = ring.SR
62
return nex
63
64
cdef public object exvector_to_PyTuple(GExVector seq):
65
"""
66
Converts arguments list given to a function to a PyTuple.
67
68
Used to pass arguments to python methods assigned to custom
69
evaluation, derivative, etc. functions of symbolic functions.
70
71
We convert Python objects wrapped in symbolic expressions back to regular
72
Python objects.
73
"""
74
from sage.symbolic.ring import SR
75
res = []
76
for i in range(seq.size()):
77
if is_a_numeric(seq.at(i)):
78
res.append(py_object_from_numeric(seq.at(i)))
79
else:
80
res.append(new_Expression_from_GEx(SR, seq.at(i)))
81
return tuple(res)
82
83
cdef public GEx pyExpression_to_ex(object res) except *:
84
"""
85
Converts an Expression object to a GiNaC::ex.
86
87
Used to pass return values of custom python evaluation, derivation
88
functions back to C++ level.
89
"""
90
if res is None:
91
raise TypeError, "function returned None, expected return value of type sage.symbolic.expression.Expression"
92
try:
93
t = ring.SR.coerce(res)
94
except TypeError, err:
95
raise TypeError, "function did not return a symbolic expression or an element that can be coerced into a symbolic expression"
96
return (<Expression>t)._gobj
97
98
cdef public object paramset_to_PyTuple(const_paramset_ref s):
99
"""
100
Converts a std::multiset<unsigned> to a PyTuple.
101
102
Used to pass a list of parameter numbers with respect to which a function
103
is differentiated to the printing functions py_print_fderivative and
104
py_latex_fderivative.
105
"""
106
cdef GParamSetIter itr = s.begin()
107
res = []
108
while itr.is_not_equal(s.end()):
109
res.append(itr.obj())
110
itr.inc()
111
return res
112
113
def paramset_from_Expression(Expression e):
114
"""
115
EXAMPLES::
116
117
sage: from sage.symbolic.pynac import paramset_from_Expression
118
sage: f = function('f')
119
sage: paramset_from_Expression(f(x).diff(x))
120
[0L]
121
"""
122
return paramset_to_PyTuple(ex_to_fderivative(e._gobj).get_parameter_set())
123
124
cdef int GINAC_FN_SERIAL = 0
125
126
cdef set_ginac_fn_serial():
127
"""
128
Initialize the GINAC_FN_SERIAL variable to the number of functions
129
defined by GiNaC. This allows us to prevent collisions with C++ level
130
special functions when a user asks to construct a symbolic function
131
with the same name.
132
"""
133
global GINAC_FN_SERIAL
134
GINAC_FN_SERIAL = g_registered_functions().size()
135
136
cdef public int py_get_ginac_serial():
137
"""
138
Returns the number of C++ level functions defined by GiNaC.
139
140
EXAMPLES::
141
142
sage: from sage.symbolic.pynac import get_ginac_serial
143
sage: get_ginac_serial() >= 40
144
True
145
"""
146
global GINAC_FN_SERIAL
147
return GINAC_FN_SERIAL
148
149
def get_ginac_serial():
150
"""
151
Number of C++ level functions defined by GiNaC. (Defined mainly for testing.)
152
153
EXAMPLES::
154
155
sage: sage.symbolic.pynac.get_ginac_serial() >= 40
156
True
157
"""
158
return py_get_ginac_serial()
159
160
#################################################################
161
# Printing helpers
162
#################################################################
163
164
##########################################################################
165
# Pynac's precedence levels, as extracted from the raw source code on
166
# 2009-05-15. If this changes in Pynac it could cause a bug in
167
# printing. But it's hardcoded in Pynac now, so there's not much to
168
# be done (at present).
169
# Container: 10
170
# Expairseq: 10
171
# Relational: 20
172
# Numeric: 30
173
# Pseries: 38
174
# Addition: 40
175
# Integral: 45
176
# Multiplication: 50
177
# Noncummative mult: 50
178
# Index: 55
179
# Power: 60
180
# Clifford: 65
181
# Function: 70
182
# Structure: 70
183
##########################################################################
184
185
cdef public stdstring* py_repr(object o, int level) except +:
186
"""
187
Return string representation of o. If level > 0, possibly put
188
parentheses around the string.
189
"""
190
s = repr(o)
191
if level >= 20:
192
# s may need parens (e.g., is in an exponent), so decide if we
193
# have to put parentheses around s:
194
# A regexp might seem better, but I don't think it's really faster.
195
# It would be more readable. Python does the below (with in) very quickly.
196
if level <= 50:
197
t = s[1:] # ignore leading minus
198
else:
199
t = s
200
# Python complexes are always printed with parentheses
201
# we try to avoid double parantheses
202
if not PY_TYPE_CHECK_EXACT(o, complex) and \
203
(' ' in t or '/' in t or '+' in t or '-' in t or '*' in t \
204
or '^' in t):
205
s = '(%s)'%s
206
return string_from_pystr(s)
207
208
cdef public stdstring* py_latex(object o, int level) except +:
209
"""
210
Return latex string representation of o. If level > 0, possibly
211
put parentheses around the string.
212
"""
213
from sage.misc.latex import latex
214
s = latex(o)
215
if level >= 20:
216
if ' ' in s or '/' in s or '+' in s or '-' in s or '*' in s or '^' in s or '\\frac' in s:
217
s = '\\left(%s\\right)'%s
218
return string_from_pystr(s)
219
220
cdef stdstring* string_from_pystr(object py_str):
221
"""
222
Creates a C++ string with the same contents as the given python string.
223
224
Used when passing string output to Pynac for printing, since we don't want
225
to mess with reference counts of the python objects and we cannot guarantee
226
they won't be garbage collected before the output is printed.
227
228
WARNING: You *must* call this with py_str a str type, or it will segfault.
229
"""
230
cdef char *t_str = PyString_AsString(py_str)
231
cdef Py_ssize_t slen = len(py_str)
232
cdef stdstring* sout = stdstring_construct_cstr(t_str, slen)
233
return sout
234
235
cdef public stdstring* py_latex_variable(char* var_name) except +:
236
"""
237
Returns a c++ string containing the latex representation of the given
238
variable name.
239
240
Real work is done by the function sage.misc.latex.latex_variable_name.
241
242
EXAMPLES::
243
244
sage: from sage.symbolic.pynac import py_latex_variable_for_doctests
245
sage: py_latex_variable = py_latex_variable_for_doctests
246
247
sage: py_latex_variable('a')
248
a
249
sage: py_latex_variable('abc')
250
\mbox{abc}
251
sage: py_latex_variable('a_00')
252
a_{00}
253
sage: py_latex_variable('sigma_k')
254
\sigma_{k}
255
sage: py_latex_variable('sigma389')
256
\sigma_{389}
257
sage: py_latex_variable('beta_00')
258
\beta_{00}
259
"""
260
cdef Py_ssize_t slen
261
from sage.misc.latex import latex_variable_name
262
py_vlatex = latex_variable_name(var_name)
263
return string_from_pystr(py_vlatex)
264
265
def py_latex_variable_for_doctests(x):
266
"""
267
Internal function used so we can doctest a certain cdef'd method.
268
269
EXAMPLES::
270
271
sage: sage.symbolic.pynac.py_latex_variable_for_doctests('x')
272
x
273
sage: sage.symbolic.pynac.py_latex_variable_for_doctests('sigma')
274
\sigma
275
"""
276
assert isinstance(x, str)
277
cdef stdstring* ostr = py_latex_variable(PyString_AsString(x))
278
print(ostr.c_str())
279
stdstring_delete(ostr)
280
281
def py_print_function_pystring(id, args, fname_paren=False):
282
"""
283
Return a string with the representation of the symbolic function specified
284
by the given id applied to args.
285
286
INPUT:
287
288
id -- serial number of the corresponding symbolic function
289
params -- Set of parameter numbers with respect to which to take
290
the derivative.
291
args -- arguments of the function.
292
293
EXAMPLES::
294
295
sage: from sage.symbolic.pynac import py_print_function_pystring, get_ginac_serial
296
sage: from sage.symbolic.function import get_sfunction_from_serial
297
sage: var('x,y,z')
298
(x, y, z)
299
sage: foo = function('foo', nargs=2)
300
sage: for i in range(get_ginac_serial(), get_ginac_serial()+50):
301
... if get_sfunction_from_serial(i) == foo: break
302
303
sage: get_sfunction_from_serial(i) == foo
304
True
305
sage: py_print_function_pystring(i, (x,y))
306
'foo(x, y)'
307
sage: py_print_function_pystring(i, (x,y), True)
308
'(foo)(x, y)'
309
sage: def my_print(self, *args): return "my args are: " + ', '.join(map(repr, args))
310
sage: foo = function('foo', nargs=2, print_func=my_print)
311
sage: for i in range(get_ginac_serial(), get_ginac_serial()+50):
312
... if get_sfunction_from_serial(i) == foo: break
313
314
sage: get_sfunction_from_serial(i) == foo
315
True
316
sage: py_print_function_pystring(i, (x,y))
317
'my args are: x, y'
318
"""
319
cdef Function func = get_sfunction_from_serial(id)
320
# This function is called from two places, from function::print in Pynac
321
# and from py_print_fderivative. function::print checks if the serial
322
# belongs to a function defined at the C++ level. There are no C++ level
323
# functions that return an instance of fderivative when derivated. Hence,
324
# func will never be None.
325
assert(func is not None)
326
327
# if function has a custom print function call it
328
if hasattr(func,'_print_'):
329
res = func._print_(*args)
330
# make sure the output is a string
331
if res is None:
332
return ""
333
if not isinstance(res, str):
334
return str(res)
335
return res
336
337
# otherwise use default output
338
if fname_paren:
339
olist = ['(', func._name, ')']
340
else:
341
olist = [func._name]
342
olist.extend(['(', ', '.join(map(repr, args)), ')'])
343
return ''.join(olist)
344
345
cdef public stdstring* py_print_function(unsigned id, object args) except +:
346
return string_from_pystr(py_print_function_pystring(id, args))
347
348
def py_latex_function_pystring(id, args, fname_paren=False):
349
"""
350
Return a string with the latex representation of the symbolic function
351
specified by the given id applied to args.
352
353
See documentation of py_print_function_pystring for more information.
354
355
EXAMPLES::
356
357
sage: from sage.symbolic.pynac import py_latex_function_pystring, get_ginac_serial
358
sage: from sage.symbolic.function import get_sfunction_from_serial
359
sage: var('x,y,z')
360
(x, y, z)
361
sage: foo = function('foo', nargs=2)
362
sage: for i in range(get_ginac_serial(), get_ginac_serial()+50):
363
... if get_sfunction_from_serial(i) == foo: break
364
365
sage: get_sfunction_from_serial(i) == foo
366
True
367
sage: py_latex_function_pystring(i, (x,y^z))
368
'{\\rm foo}\\left(x, y^{z}\\right)'
369
sage: py_latex_function_pystring(i, (x,y^z), True)
370
'\\left({\\rm foo}\\right)\\left(x, y^{z}\\right)'
371
372
Test latex_name::
373
374
sage: foo = function('foo', nargs=2, latex_name=r'\mathrm{bar}')
375
sage: for i in range(get_ginac_serial(), get_ginac_serial()+50):
376
... if get_sfunction_from_serial(i) == foo: break
377
378
sage: get_sfunction_from_serial(i) == foo
379
True
380
sage: py_latex_function_pystring(i, (x,y^z))
381
'\\mathrm{bar}\\left(x, y^{z}\\right)'
382
383
Test custom func::
384
385
sage: def my_print(self, *args): return "my args are: " + ', '.join(map(repr, args))
386
sage: foo = function('foo', nargs=2, print_latex_func=my_print)
387
sage: for i in range(get_ginac_serial(), get_ginac_serial()+50):
388
... if get_sfunction_from_serial(i) == foo: break
389
390
sage: get_sfunction_from_serial(i) == foo
391
True
392
sage: py_latex_function_pystring(i, (x,y^z))
393
'my args are: x, y^z'
394
395
396
"""
397
cdef Function func = get_sfunction_from_serial(id)
398
# This function is called from two places, from function::print in Pynac
399
# and from py_latex_fderivative. function::print checks if the serial
400
# belongs to a function defined at the C++ level. There are no C++ level
401
# functions that return an instance of fderivative when derivated. Hence,
402
# func will never be None.
403
assert(func is not None)
404
405
# if function has a custom print method call it
406
if hasattr(func, '_print_latex_'):
407
res = func._print_latex_(*args)
408
# make sure the output is a string
409
if res is None:
410
return ""
411
if not isinstance(res, str):
412
return str(res)
413
return res
414
415
# otherwise, use the latex name if defined
416
if func._latex_name:
417
name = func._latex_name
418
else:
419
# if latex_name is not defined, then call
420
# latex_variable_name with "is_fname=True" flag
421
from sage.misc.latex import latex_variable_name
422
name = latex_variable_name(func._name, is_fname=True)
423
if fname_paren:
424
olist = [r'\left(', name, r'\right)']
425
else:
426
olist = [name]
427
# print the arguments
428
olist.extend([r'\left(', ', '.join([x._latex_() for x in args]),
429
r'\right)'] )
430
return ''.join(olist)
431
432
cdef public stdstring* py_latex_function(unsigned id, object args) except +:
433
return string_from_pystr(py_latex_function_pystring(id, args))
434
435
cdef public stdstring* py_print_fderivative(unsigned id, object params,
436
object args) except +:
437
"""
438
Return a string with the representation of the derivative of the symbolic
439
function specified by the given id, lists of params and args.
440
441
INPUT:
442
443
id -- serial number of the corresponding symbolic function
444
params -- Set of parameter numbers with respect to which to take
445
the derivative.
446
args -- arguments of the function.
447
448
449
"""
450
ostr = ''.join(['D[', ', '.join([repr(int(x)) for x in params]), ']'])
451
fstr = py_print_function_pystring(id, args, True)
452
py_res = ostr + fstr
453
return string_from_pystr(py_res)
454
455
def py_print_fderivative_for_doctests(id, params, args):
456
"""
457
Used for testing a cdef'd function.
458
459
EXAMPLES::
460
461
sage: from sage.symbolic.pynac import py_print_fderivative_for_doctests as py_print_fderivative, get_ginac_serial
462
463
sage: var('x,y,z')
464
(x, y, z)
465
sage: from sage.symbolic.function import get_sfunction_from_serial
466
sage: foo = function('foo', nargs=2)
467
sage: for i in range(get_ginac_serial(), get_ginac_serial()+50):
468
... if get_sfunction_from_serial(i) == foo: break
469
470
sage: get_sfunction_from_serial(i) == foo
471
True
472
sage: py_print_fderivative(i, (0, 1, 0, 1), (x, y^z))
473
D[0, 1, 0, 1](foo)(x, y^z)
474
475
Test custom print function::
476
477
sage: def my_print(self, *args): return "func_with_args(" + ', '.join(map(repr, args)) +')'
478
sage: foo = function('foo', nargs=2, print_func=my_print)
479
sage: for i in range(get_ginac_serial(), get_ginac_serial()+50):
480
... if get_sfunction_from_serial(i) == foo: break
481
482
sage: get_sfunction_from_serial(i) == foo
483
True
484
sage: py_print_fderivative(i, (0, 1, 0, 1), (x, y^z))
485
D[0, 1, 0, 1]func_with_args(x, y^z)
486
487
"""
488
cdef stdstring* ostr = py_print_fderivative(id, params, args)
489
print(ostr.c_str())
490
stdstring_delete(ostr)
491
492
cdef public stdstring* py_latex_fderivative(unsigned id, object params,
493
object args) except +:
494
"""
495
Return a string with the latex representation of the derivative of the
496
symbolic function specified by the given id, lists of params and args.
497
498
See documentation of py_print_fderivative for more information.
499
500
"""
501
ostr = ''.join(['D[', ', '.join([repr(int(x)) for x in params]), ']'])
502
fstr = py_latex_function_pystring(id, args, True)
503
py_res = ostr + fstr
504
return string_from_pystr(py_res)
505
506
def py_latex_fderivative_for_doctests(id, params, args):
507
"""
508
Used internally for writing doctests for certain cdef'd functions.
509
510
EXAMPLES::
511
512
sage: from sage.symbolic.pynac import py_latex_fderivative_for_doctests as py_latex_fderivative, get_ginac_serial
513
514
sage: var('x,y,z')
515
(x, y, z)
516
sage: from sage.symbolic.function import get_sfunction_from_serial
517
sage: foo = function('foo', nargs=2)
518
sage: for i in range(get_ginac_serial(), get_ginac_serial()+50):
519
... if get_sfunction_from_serial(i) == foo: break
520
521
sage: get_sfunction_from_serial(i) == foo
522
True
523
sage: py_latex_fderivative(i, (0, 1, 0, 1), (x, y^z))
524
D[0, 1, 0, 1]\left({\rm foo}\right)\left(x, y^{z}\right)
525
526
Test latex_name::
527
528
sage: foo = function('foo', nargs=2, latex_name=r'\mathrm{bar}')
529
sage: for i in range(get_ginac_serial(), get_ginac_serial()+50):
530
... if get_sfunction_from_serial(i) == foo: break
531
532
sage: get_sfunction_from_serial(i) == foo
533
True
534
sage: py_latex_fderivative(i, (0, 1, 0, 1), (x, y^z))
535
D[0, 1, 0, 1]\left(\mathrm{bar}\right)\left(x, y^{z}\right)
536
537
Test custom func::
538
539
sage: def my_print(self, *args): return "func_with_args(" + ', '.join(map(repr, args)) +')'
540
sage: foo = function('foo', nargs=2, print_latex_func=my_print)
541
sage: for i in range(get_ginac_serial(), get_ginac_serial()+50):
542
... if get_sfunction_from_serial(i) == foo: break
543
544
sage: get_sfunction_from_serial(i) == foo
545
True
546
sage: py_latex_fderivative(i, (0, 1, 0, 1), (x, y^z))
547
D[0, 1, 0, 1]func_with_args(x, y^z)
548
"""
549
cdef stdstring* ostr = py_latex_fderivative(id, params, args)
550
print(ostr.c_str())
551
stdstring_delete(ostr)
552
553
#################################################################
554
# Archive helpers
555
#################################################################
556
557
from sage.structure.sage_object import loads, dumps
558
cdef public stdstring* py_dumps(object o) except +:
559
s = dumps(o, compress=False)
560
# pynac archive format terminates atoms with zeroes.
561
# since pickle output can break the archive format
562
# we use the base64 data encoding
563
import base64
564
s = base64.b64encode(s)
565
return string_from_pystr(s)
566
567
cdef public object py_loads(object s) except +:
568
import base64
569
s = base64.b64decode(s)
570
return loads(s)
571
572
cdef public object py_get_sfunction_from_serial(unsigned s) except +:
573
"""
574
Return the Python object associated with a serial.
575
"""
576
return get_sfunction_from_serial(s)
577
578
cdef public unsigned py_get_serial_from_sfunction(object f) except +:
579
"""
580
Given a Function object return its serial.
581
582
Python's unpickling mechanism is used to unarchive a symbolic function with
583
custom methods (evaluation, differentiation, etc.). Pynac extracts a string
584
representation from the archive, calls loads() to recreate the stored
585
function. This allows us to extract the serial from the Python object to
586
set the corresponding member variable of the C++ object representing this
587
function.
588
"""
589
return (<Function>f)._serial
590
591
cdef public unsigned py_get_serial_for_new_sfunction(stdstring &s,
592
unsigned nargs) except +:
593
"""
594
Return a symbolic function with the given name and number of arguments.
595
596
When unarchiving a user defined symbolic function, Pynac goes through
597
the registry of existing functions. If there is no function already defined
598
with the archived name and number of arguments, this method is called to
599
create one and set up the function tables properly.
600
"""
601
from sage.symbolic.function_factory import function_factory
602
cdef Function fn = function_factory(s.c_str(), nargs)
603
return fn._serial
604
605
606
#################################################################
607
# Modular helpers
608
#################################################################
609
610
from sage.structure.element cimport Element
611
612
# We declare the functions defined below as extern here, to prevent Cython
613
# from generating separate declarations for them which confuse g++
614
cdef extern from *:
615
int py_get_parent_char(object o) except -1
616
617
cdef public int py_get_parent_char(object o) except -1:
618
if isinstance(o, Element):
619
return (<Element>o)._parent.characteristic()
620
else:
621
return 0
622
623
#################################################################
624
# power helpers
625
#################################################################
626
627
628
from sage.rings.rational cimport rational_power_parts
629
cdef public object py_rational_power_parts(object base, object exp) except +:
630
if not PY_TYPE_CHECK_EXACT(base, Rational):
631
base = Rational(base)
632
if not PY_TYPE_CHECK_EXACT(exp, Rational):
633
exp = Rational(exp)
634
res= rational_power_parts(base, exp)
635
return res + (bool(res[0] == 1),)
636
637
#################################################################
638
# Binomial Coefficients
639
#################################################################
640
641
642
cdef public object py_binomial_int(int n, unsigned int k) except +:
643
cdef bint sign
644
if n < 0:
645
n = -n + (k-1)
646
sign = k%2
647
else:
648
sign = 0
649
cdef Integer ans = PY_NEW(Integer)
650
# Compute the binomial coefficient using GMP.
651
mpz_bin_uiui(ans.value, n, k)
652
# Return the answer or the negative of it (only if k is odd and n is negative).
653
if sign:
654
return -ans
655
else:
656
return ans
657
658
cdef public object py_binomial(object n, object k) except +:
659
# Keep track of the sign we should use.
660
cdef bint sign
661
if n < 0:
662
n = k-n-1
663
sign = k%2
664
else:
665
sign = 0
666
# Convert n and k to unsigned ints.
667
cdef unsigned int n_ = n, k_ = k
668
cdef Integer ans = PY_NEW(Integer)
669
# Compute the binomial coefficient using GMP.
670
mpz_bin_uiui(ans.value, n_, k_)
671
# Return the answer or the negative of it (only if k is odd and n is negative).
672
if sign:
673
return -ans
674
else:
675
return ans
676
677
def test_binomial(n, k):
678
"""
679
The Binomial coefficients. It computes the binomial coefficients. For
680
integer n and k and positive n this is the number of ways of choosing k
681
objects from n distinct objects. If n is negative, the formula
682
binomial(n,k) == (-1)^k*binomial(k-n-1,k) is used to compute the result.
683
684
INPUT:
685
n, k -- integers, with k >= 0.
686
687
OUTPUT:
688
integer
689
690
EXAMPLES::
691
692
sage: import sage.symbolic.pynac
693
sage: sage.symbolic.pynac.test_binomial(5,2)
694
10
695
sage: sage.symbolic.pynac.test_binomial(-5,3)
696
-35
697
sage: -sage.symbolic.pynac.test_binomial(3-(-5)-1, 3)
698
-35
699
"""
700
return py_binomial(n, k)
701
702
#################################################################
703
# GCD
704
#################################################################
705
import sage.rings.arith
706
cdef public object py_gcd(object n, object k) except +:
707
if PY_TYPE_CHECK(n, Integer) and PY_TYPE_CHECK(k, Integer):
708
if mpz_cmp_si((<Integer>n).value,1) == 0:
709
return n
710
elif mpz_cmp_si((<Integer>k).value,1) == 0:
711
return k
712
return n.gcd(k)
713
714
if PY_TYPE_CHECK_EXACT(n, Rational) and PY_TYPE_CHECK_EXACT(k, Rational):
715
return n.content(k)
716
try:
717
return sage.rings.arith.gcd(n,k)
718
except (TypeError, ValueError, AttributeError):
719
# some strange meaning in case of weird things with no usual lcm.
720
return 1
721
722
723
#################################################################
724
# LCM
725
#################################################################
726
cdef public object py_lcm(object n, object k) except +:
727
if PY_TYPE_CHECK(n, Integer) and PY_TYPE_CHECK(k, Integer):
728
if mpz_cmp_si((<Integer>n).value,1) == 0:
729
return k
730
elif mpz_cmp_si((<Integer>k).value,1) == 0:
731
return n
732
return n.lcm(k)
733
try:
734
return sage.rings.arith.lcm(n,k)
735
except (TypeError, ValueError, AttributeError):
736
# some strange meaning in case of weird things with no usual lcm, e.g.,
737
# elements of finite fields.
738
return 1
739
740
741
#################################################################
742
# Real Part
743
#################################################################
744
cdef public object py_real(object x) except +:
745
"""
746
Returns the real part of x.
747
748
TESTS::
749
750
sage: from sage.symbolic.pynac import py_real_for_doctests as py_real
751
sage: py_real(I)
752
0
753
sage: py_real(CC(1,5))
754
1.00000000000000
755
sage: py_real(CC(1))
756
1.00000000000000
757
sage: py_real(RR(1))
758
1.00000000000000
759
760
sage: py_real(Mod(2,7))
761
2
762
763
sage: py_real(QQ['x'].gen())
764
x
765
sage: py_real(float(2))
766
2.0
767
sage: py_real(complex(2,2))
768
2.0
769
"""
770
if PY_TYPE_CHECK_EXACT(x, float) or PY_TYPE_CHECK_EXACT(x, int) or \
771
PY_TYPE_CHECK_EXACT(x, long):
772
return x
773
elif PY_TYPE_CHECK_EXACT(x, complex):
774
return x.real
775
776
try:
777
return x.real()
778
except AttributeError:
779
pass
780
try:
781
return x.real_part()
782
except AttributeError:
783
pass
784
785
return x # assume x is real
786
787
def py_real_for_doctests(x):
788
"""
789
Used for doctesting py_real.
790
791
TESTS::
792
793
sage: from sage.symbolic.pynac import py_real_for_doctests
794
sage: py_real_for_doctests(I)
795
0
796
"""
797
return py_real(x)
798
799
#################################################################
800
# Imaginary Part
801
#################################################################
802
cdef public object py_imag(object x) except +:
803
"""
804
Return the imaginary part of x.
805
806
TESTS::
807
808
sage: from sage.symbolic.pynac import py_imag_for_doctests as py_imag
809
sage: py_imag(I)
810
1
811
sage: py_imag(CC(1,5))
812
5.00000000000000
813
sage: py_imag(CC(1))
814
0.000000000000000
815
sage: py_imag(RR(1))
816
0
817
sage: py_imag(Mod(2,7))
818
0
819
820
sage: py_imag(QQ['x'].gen())
821
0
822
sage: py_imag(float(2))
823
0.0
824
sage: py_imag(complex(2,2))
825
2.0
826
"""
827
if PY_TYPE_CHECK_EXACT(x, float):
828
return float(0)
829
if PY_TYPE_CHECK_EXACT(x, complex):
830
return x.imag
831
try:
832
return x.imag()
833
except AttributeError:
834
pass
835
try:
836
return x.imag_part()
837
except AttributeError:
838
pass
839
840
841
return 0 # assume x is real
842
843
def py_imag_for_doctests(x):
844
"""
845
Used for doctesting py_imag.
846
847
TESTS::
848
849
sage: from sage.symbolic.pynac import py_imag_for_doctests
850
sage: py_imag_for_doctests(I)
851
1
852
"""
853
return py_imag(x)
854
855
856
#################################################################
857
# Conjugate
858
#################################################################
859
cdef public object py_conjugate(object x) except +:
860
try:
861
return x.conjugate()
862
except AttributeError:
863
return x # assume is real since it doesn't have an imag attribute.
864
865
cdef public bint py_is_rational(object x) except +:
866
return PY_TYPE_CHECK_EXACT(x, Rational) or \
867
PY_TYPE_CHECK_EXACT(x, Integer) or\
868
IS_INSTANCE(x, int) or IS_INSTANCE(x, long)
869
870
cdef public bint py_is_equal(object x, object y) except +:
871
"""
872
Return True precisely if x and y are equal.
873
"""
874
return bool(x==y)
875
876
cdef public bint py_is_integer(object x) except +:
877
r"""
878
Returns True if pynac should treat this object as an integer.
879
880
EXAMPLES::
881
882
sage: from sage.symbolic.pynac import py_is_integer_for_doctests
883
sage: py_is_integer = py_is_integer_for_doctests
884
885
sage: py_is_integer(1r)
886
True
887
sage: py_is_integer(long(1))
888
True
889
sage: py_is_integer(3^57)
890
True
891
sage: py_is_integer(SR(5))
892
True
893
sage: py_is_integer(4/2)
894
True
895
sage: py_is_integer(QQbar(sqrt(2))^2)
896
True
897
sage: py_is_integer(3.0)
898
False
899
sage: py_is_integer(3.0r)
900
False
901
"""
902
return IS_INSTANCE(x, int) or IS_INSTANCE(x, long) or PY_TYPE_CHECK(x, Integer) or \
903
(IS_INSTANCE(x, Element) and
904
((<Element>x)._parent.is_exact() or (<Element>x)._parent == ring.SR) and
905
(x in ZZ))
906
907
def py_is_integer_for_doctests(x):
908
"""
909
Used internally for doctesting purposes.
910
911
TESTS::
912
913
sage: sage.symbolic.pynac.py_is_integer_for_doctests(1r)
914
True
915
sage: sage.symbolic.pynac.py_is_integer_for_doctests(1/3)
916
False
917
sage: sage.symbolic.pynac.py_is_integer_for_doctests(2)
918
True
919
"""
920
return py_is_integer(x)
921
922
cdef public bint py_is_even(object x) except +:
923
try:
924
return not(x%2)
925
except:
926
try:
927
return not(ZZ(x)%2)
928
except:
929
pass
930
return 0
931
932
933
cdef public bint py_is_crational(object x) except +:
934
if py_is_rational(x):
935
return True
936
elif isinstance(x, Element) and (<Element>x)._parent is pynac_I._parent:
937
return True
938
else:
939
return False
940
941
def py_is_crational_for_doctest(x):
942
"""
943
Returns True if pynac should treat this object as an element of `\QQ(i)`.
944
945
TESTS::
946
947
sage: from sage.symbolic.pynac import py_is_crational_for_doctest
948
sage: py_is_crational_for_doctest(1)
949
True
950
sage: py_is_crational_for_doctest(-2r)
951
True
952
sage: py_is_crational_for_doctest(1.5)
953
False
954
sage: py_is_crational_for_doctest(I.pyobject())
955
True
956
sage: py_is_crational_for_doctest(I.pyobject()+1/2)
957
True
958
"""
959
return py_is_crational(x)
960
961
cdef public bint py_is_real(object a) except +:
962
if PyInt_CheckExact(a) or PY_TYPE_CHECK(a, Integer) or\
963
PyLong_CheckExact(a) or PY_TYPE_CHECK_EXACT(a, float):
964
return True
965
return py_imag(a) == 0
966
967
import sage.rings.arith
968
cdef public bint py_is_prime(object n) except +:
969
try:
970
return n.is_prime()
971
except: # yes, I'm doing this on purpose.
972
pass
973
try:
974
return sage.rings.arith.is_prime(n)
975
except:
976
pass
977
return False
978
979
cdef public object py_numer(object n) except +:
980
"""
981
Return the numerator of the given object. This is called for
982
typesetting coefficients.
983
984
TESTS::
985
986
sage: from sage.symbolic.pynac import py_numer_for_doctests as py_numer
987
sage: py_numer(2r)
988
2
989
sage: py_numer(3)
990
3
991
sage: py_numer(2/3)
992
2
993
sage: C.<i> = NumberField(x^2+1)
994
sage: py_numer(2/3*i)
995
2*i
996
sage: class no_numer:
997
... def denominator(self):
998
... return 5
999
... def __mul__(left, right):
1000
... return 42
1001
...
1002
sage: py_numer(no_numer())
1003
42
1004
"""
1005
if isinstance(n, (int, long, Integer)):
1006
return n
1007
try:
1008
return n.numerator()
1009
except AttributeError:
1010
try:
1011
return n*n.denominator()
1012
except AttributeError:
1013
return n
1014
1015
def py_numer_for_doctests(n):
1016
"""
1017
This function is used to test py_numer().
1018
1019
EXAMPLES::
1020
1021
sage: from sage.symbolic.pynac import py_numer_for_doctests
1022
sage: py_numer_for_doctests(2/3)
1023
2
1024
"""
1025
return py_numer(n)
1026
1027
cdef public object py_denom(object n) except +:
1028
"""
1029
Return the denominator of the given object. This is called for
1030
typesetting coefficients.
1031
1032
TESTS::
1033
1034
sage: from sage.symbolic.pynac import py_denom_for_doctests as py_denom
1035
sage: py_denom(5)
1036
1
1037
sage: py_denom(2/3)
1038
3
1039
sage: C.<i> = NumberField(x^2+1)
1040
sage: py_denom(2/3*i)
1041
3
1042
"""
1043
if isinstance(n, (int, long, Integer)):
1044
return 1
1045
try:
1046
return n.denominator()
1047
except AttributeError:
1048
return 1
1049
1050
def py_denom_for_doctests(n):
1051
"""
1052
This function is used to test py_denom().
1053
1054
EXAMPLES::
1055
1056
sage: from sage.symbolic.pynac import py_denom_for_doctests
1057
sage: py_denom_for_doctests(2/3)
1058
3
1059
"""
1060
return py_denom(n)
1061
1062
cdef public bint py_is_cinteger(object x) except +:
1063
return py_is_integer(x) or (py_is_crational(x) and py_denom(x) == 1)
1064
1065
def py_is_cinteger_for_doctest(x):
1066
"""
1067
Returns True if pynac should treat this object as an element of `\ZZ(i)`.
1068
1069
TESTS::
1070
1071
sage: from sage.symbolic.pynac import py_is_cinteger_for_doctest
1072
sage: py_is_cinteger_for_doctest(1)
1073
True
1074
sage: py_is_cinteger_for_doctest(long(-3))
1075
True
1076
sage: py_is_cinteger_for_doctest(I.pyobject())
1077
True
1078
sage: py_is_cinteger_for_doctest(I.pyobject() - 3)
1079
True
1080
sage: py_is_cinteger_for_doctest(I.pyobject() + 1/2)
1081
False
1082
"""
1083
return py_is_cinteger(x)
1084
1085
cdef public object py_float(object n, PyObject* parent) except +:
1086
"""
1087
Evaluate pynac numeric objects numerically.
1088
1089
TESTS::
1090
1091
sage: from sage.symbolic.pynac import py_float_for_doctests as py_float
1092
sage: py_float(I, ComplexField(10))
1093
1.0*I
1094
sage: py_float(pi, RealField(100))
1095
3.1415926535897932384626433833
1096
sage: py_float(10, CDF)
1097
10.0
1098
sage: type(py_float(10, CDF))
1099
<type 'sage.rings.complex_double.ComplexDoubleElement'>
1100
sage: py_float(1/2, CC)
1101
0.500000000000000
1102
sage: type(py_float(1/2, CC))
1103
<type 'sage.rings.complex_number.ComplexNumber'>
1104
"""
1105
if parent is not NULL:
1106
return (<object>parent)(n)
1107
else:
1108
try:
1109
return RR(n)
1110
except TypeError:
1111
return CC(n)
1112
1113
def py_float_for_doctests(n, prec):
1114
"""
1115
This function is for testing py_float.
1116
1117
EXAMPLES::
1118
1119
sage: from sage.symbolic.pynac import py_float_for_doctests
1120
sage: py_float_for_doctests(pi, RealField(80))
1121
3.1415926535897932384626
1122
"""
1123
return py_float(n, <PyObject*>prec)
1124
1125
# TODO: Optimize this
1126
from sage.rings.real_double import RDF
1127
cdef public object py_RDF_from_double(double x) except +:
1128
return RDF(x)
1129
1130
#################################################################
1131
# SPECIAL FUNCTIONS
1132
#################################################################
1133
cdef public object py_tgamma(object x) except +:
1134
"""
1135
The gamma function exported to pynac.
1136
1137
TESTS::
1138
1139
sage: from sage.symbolic.pynac import py_tgamma_for_doctests as py_tgamma
1140
sage: py_tgamma(4)
1141
6
1142
sage: py_tgamma(1/2)
1143
1.77245385090552
1144
"""
1145
if PY_TYPE_CHECK_EXACT(x, int) or PY_TYPE_CHECK_EXACT(x, long):
1146
x = float(x)
1147
if PY_TYPE_CHECK_EXACT(x, float):
1148
return sage_tgammal(x)
1149
1150
# try / except blocks are faster than
1151
# if hasattr(x, 'gamma')
1152
try:
1153
res = x.gamma()
1154
except AttributeError:
1155
return CC(x).gamma()
1156
1157
# the result should be numeric, however the gamma method of rationals may
1158
# return symbolic expressions. for example (1/2).gamma() -> sqrt(pi).
1159
if isinstance(res, Expression):
1160
try:
1161
return RR(res)
1162
except ValueError:
1163
return CC(res)
1164
return res
1165
1166
def py_tgamma_for_doctests(x):
1167
"""
1168
This function is for testing py_tgamma().
1169
1170
TESTS::
1171
1172
sage: from sage.symbolic.pynac import py_tgamma_for_doctests
1173
sage: py_tgamma_for_doctests(3)
1174
2
1175
"""
1176
return py_tgamma(x)
1177
1178
from sage.rings.arith import factorial
1179
cdef public object py_factorial(object x) except +:
1180
"""
1181
The factorial function exported to pynac.
1182
1183
TESTS::
1184
1185
sage: from sage.symbolic.pynac import py_factorial_py as py_factorial
1186
sage: py_factorial(4)
1187
24
1188
sage: py_factorial(-2/3)
1189
2.67893853470775
1190
"""
1191
# factorial(x) is only defined for non-negative integers x
1192
# so we first test if x can be coerced into ZZ and is non-negative.
1193
# If this is not the case then we return the symbolic expression gamma(x+1)
1194
# This fixes Trac 9240
1195
try:
1196
x_in_ZZ = ZZ(x)
1197
coercion_success = True
1198
except TypeError:
1199
coercion_success = False
1200
1201
if coercion_success and x_in_ZZ >= 0:
1202
return factorial(x)
1203
else:
1204
return py_tgamma(x+1)
1205
1206
def py_factorial_py(x):
1207
"""
1208
This function is a python wrapper around py_factorial(). This wrapper
1209
is needed when we override the eval() method for GiNaC's factorial
1210
function in sage.functions.other.Function_factorial.
1211
1212
TESTS::
1213
1214
sage: from sage.symbolic.pynac import py_factorial_py
1215
sage: py_factorial_py(3)
1216
6
1217
"""
1218
return py_factorial(x)
1219
1220
cdef public object py_doublefactorial(object x) except +:
1221
n = Integer(x)
1222
if n < -1:
1223
raise ValueError, "argument must be >= -1"
1224
from sage.misc.misc_c import prod # fast balanced product
1225
return prod([n - 2*i for i in range(n//2)])
1226
1227
def doublefactorial(n):
1228
"""
1229
The double factorial combinatorial function:
1230
n!! == n * (n-2) * (n-4) * ... * ({1|2}) with 0!! == (-1)!! == 1.
1231
1232
INPUT:
1233
n -- an integer > = 1
1234
1235
EXAMPLES::
1236
1237
sage: from sage.symbolic.pynac import doublefactorial
1238
sage: doublefactorial(-1)
1239
1
1240
sage: doublefactorial(0)
1241
1
1242
sage: doublefactorial(1)
1243
1
1244
sage: doublefactorial(5)
1245
15
1246
sage: doublefactorial(20)
1247
3715891200
1248
sage: prod( [20,18,..,2] )
1249
3715891200
1250
"""
1251
return py_doublefactorial(n)
1252
1253
1254
from sage.libs.pari.all import pari
1255
cdef public object py_fibonacci(object n) except +:
1256
return Integer(pari(n).fibonacci())
1257
1258
cdef public object py_step(object n) except +:
1259
"""
1260
Return step function of n.
1261
"""
1262
cdef int c = cmp(n, 0)
1263
if c < 0:
1264
return ZERO
1265
elif c > 0:
1266
return ONE
1267
return ONE_HALF
1268
1269
from sage.rings.arith import bernoulli
1270
cdef public object py_bernoulli(object x) except +:
1271
return bernoulli(x)
1272
1273
cdef public object py_sin(object x) except +:
1274
"""
1275
TESTS::
1276
1277
sage: sin(float(2)) #indirect doctest
1278
0.9092974268256817
1279
sage: sin(2.)
1280
0.909297426825682
1281
sage: sin(2.*I)
1282
3.62686040784702*I
1283
sage: sin(QQbar(I))
1284
1.17520119364380*I
1285
"""
1286
try:
1287
return x.sin()
1288
except AttributeError:
1289
pass
1290
try:
1291
return RR(x).sin()
1292
except (TypeError, ValueError):
1293
return CC(x).sin()
1294
1295
cdef public object py_cos(object x) except +:
1296
"""
1297
TESTS::
1298
sage: cos(float(2)) #indirect doctest
1299
-0.4161468365471424
1300
sage: cos(2.)
1301
-0.416146836547142
1302
sage: cos(2.*I)
1303
3.76219569108363
1304
sage: cos(QQbar(I))
1305
1.54308063481524
1306
"""
1307
try:
1308
return x.cos()
1309
except AttributeError:
1310
pass
1311
try:
1312
return RR(x).cos()
1313
except (TypeError, ValueError):
1314
return CC(x).cos()
1315
1316
cdef public object py_zeta(object x) except +:
1317
"""
1318
Return the value of the zeta function at the given value.
1319
1320
The value is expected to be a numerical object, in RR, CC, RDF or CDF,
1321
different from 1.
1322
1323
TESTS::
1324
1325
sage: from sage.symbolic.pynac import py_zeta_for_doctests as py_zeta
1326
sage: py_zeta(CC.0)
1327
0.00330022368532410 - 0.418155449141322*I
1328
sage: py_zeta(CDF(5))
1329
1.03692775514
1330
sage: py_zeta(RealField(100)(5))
1331
1.0369277551433699263313654865
1332
"""
1333
try:
1334
return x.zeta()
1335
except AttributeError:
1336
return CC(x).zeta()
1337
1338
def py_zeta_for_doctests(x):
1339
"""
1340
This function is for testing py_zeta().
1341
1342
EXAMPLES::
1343
1344
sage: from sage.symbolic.pynac import py_zeta_for_doctests
1345
sage: py_zeta_for_doctests(CC.0)
1346
0.00330022368532410 - 0.418155449141322*I
1347
"""
1348
return py_zeta(x)
1349
1350
# py_exp(float(1)) should return the value of e
1351
# Note, the nearest IEEE 754 value of e is NOT the same as
1352
# the correctly rounded decimal value.
1353
# The numerical value of e = 2.71828182845904523536...
1354
# Correctly rounded decimal number = 2.7182818284590452
1355
# Nearest IEEE 754 format number = 2.7182818284590451
1356
# On Sun Blade 1000 with SPARC processors = 2.7182818284590455
1357
cdef public object py_exp(object x) except +:
1358
"""
1359
Return the value of the exp function at the given value.
1360
1361
The value is expected to be a numerical object, in RR, CC, RDF or CDF.
1362
1363
TESTS::
1364
1365
sage: from sage.symbolic.pynac import py_exp_for_doctests as py_exp
1366
sage: py_exp(CC(1))
1367
2.71828182845905
1368
sage: py_exp(CC(.5*I))
1369
0.877582561890373 + 0.479425538604203*I
1370
sage: py_exp(float(1))
1371
2.718281828459045...
1372
sage: py_exp(QQbar(I))
1373
0.540302305868140 + 0.841470984807897*I
1374
"""
1375
if PY_TYPE_CHECK_EXACT(x, float):
1376
return math.exp(x)
1377
try:
1378
return x.exp()
1379
except AttributeError:
1380
pass
1381
try:
1382
return RR(x).exp()
1383
except (TypeError, ValueError):
1384
return CC(x).exp()
1385
1386
def py_exp_for_doctests(x):
1387
"""
1388
This function tests py_exp.
1389
1390
EXAMPLES::
1391
1392
sage: from sage.symbolic.pynac import py_exp_for_doctests
1393
sage: py_exp_for_doctests(CC(2))
1394
7.38905609893065
1395
"""
1396
return py_exp(x)
1397
1398
cdef public object py_log(object x) except +:
1399
"""
1400
Return the value of the log function at the given value.
1401
1402
The value is expected to be a numerical object, in RR, CC, RDF or CDF.
1403
1404
TESTS::
1405
1406
sage: from sage.symbolic.pynac import py_log_for_doctests as py_log
1407
sage: py_log(CC(e))
1408
1.00000000000000
1409
sage: py_log(CC.0)
1410
1.57079632679490*I
1411
sage: py_log(float(e))
1412
1.0
1413
sage: py_log(float(0))
1414
-inf
1415
sage: py_log(float(-1))
1416
3.141592653589793j
1417
sage: py_log(int(1))
1418
0.0
1419
sage: py_log(long(1))
1420
0.0
1421
sage: py_log(int(0))
1422
-inf
1423
sage: py_log(long(0))
1424
-inf
1425
sage: py_log(complex(0))
1426
-inf
1427
sage: py_log(2)
1428
0.693147180559945
1429
"""
1430
cdef gsl_complex res
1431
cdef double real, imag
1432
if PY_TYPE_CHECK_EXACT(x, int) or PY_TYPE_CHECK_EXACT(x, long):
1433
x = float(x)
1434
if PY_TYPE_CHECK_EXACT(x, float):
1435
if (<float>x) > 0:
1436
return sage_logl(x)
1437
elif x < 0:
1438
res = gsl_complex_log(gsl_complex_rect(PyFloat_AsDouble(x), 0))
1439
return PyComplex_FromDoubles(res.dat[0], res.dat[1])
1440
else:
1441
return float('-inf')
1442
elif PY_TYPE_CHECK_EXACT(x, complex):
1443
real = PyComplex_RealAsDouble(x)
1444
imag = PyComplex_ImagAsDouble(x)
1445
if real == 0 and imag == 0:
1446
return float('-inf')
1447
res = gsl_complex_log(gsl_complex_rect(real, imag))
1448
return PyComplex_FromDoubles(res.dat[0], res.dat[1])
1449
elif isinstance(x, Integer):
1450
return x.log().n()
1451
elif hasattr(x, 'log'):
1452
return x.log()
1453
try:
1454
return RR(x).log()
1455
except (TypeError, ValueError):
1456
return CC(x).log()
1457
1458
def py_log_for_doctests(x):
1459
"""
1460
This function tests py_log.
1461
1462
EXAMPLES::
1463
1464
sage: from sage.symbolic.pynac import py_log_for_doctests
1465
sage: py_log_for_doctests(CC(e))
1466
1.00000000000000
1467
"""
1468
return py_log(x)
1469
1470
cdef public object py_tan(object x) except +:
1471
try:
1472
return x.tan()
1473
except AttributeError:
1474
pass
1475
try:
1476
return RR(x).tan()
1477
except TypeError:
1478
return CC(x).tan()
1479
1480
cdef public object py_asin(object x) except +:
1481
try:
1482
return x.arcsin()
1483
except AttributeError:
1484
return RR(x).arcsin()
1485
1486
cdef public object py_acos(object x) except +:
1487
try:
1488
return x.arccos()
1489
except AttributeError:
1490
return RR(x).arccos()
1491
1492
cdef public object py_atan(object x) except +:
1493
try:
1494
return x.arctan()
1495
except AttributeError:
1496
return RR(x).arctan()
1497
1498
cdef public object py_atan2(object x, object y) except +:
1499
"""
1500
Return the value of the two argument arctan function at the given values.
1501
1502
The values are expected to be numerical objects, for example in RR, CC,
1503
RDF or CDF.
1504
1505
Note that the usual call signature of this function has the arguments
1506
reversed.
1507
1508
TESTS::
1509
1510
sage: from sage.symbolic.pynac import py_atan2_for_doctests as py_atan2
1511
sage: py_atan2(0, 1)
1512
1.57079632679490
1513
sage: py_atan2(0.r, 1.r)
1514
1.5707963267948966
1515
sage: CC100 = ComplexField(100)
1516
sage: py_atan2(CC100(0), CC100(1))
1517
1.5707963267948966192313216916
1518
sage: RR100 = RealField(100)
1519
sage: py_atan2(RR100(0), RR100(1))
1520
1.5707963267948966192313216916
1521
"""
1522
from sage.symbolic.constants import pi
1523
parent = parent_c(x)
1524
assert parent is parent_c(y)
1525
if parent is ZZ:
1526
parent = RR
1527
pi_n = parent(pi)
1528
cdef int sgn_y = cmp(y, 0)
1529
cdef int sgn_x = cmp(x, 0)
1530
if sgn_y:
1531
if sgn_x > 0:
1532
return py_atan(abs(y/x)) * sgn_y
1533
elif sgn_x == 0:
1534
return pi_n/2 * sgn_y
1535
else:
1536
return (pi_n - py_atan(abs(y/x))) * sgn_y
1537
else:
1538
if sgn_x > 0:
1539
return 0
1540
elif x == 0:
1541
raise ValueError, "arctan2(0,0) undefined"
1542
else:
1543
return pi_n
1544
1545
def py_atan2_for_doctests(x, y):
1546
"""
1547
Wrapper function to test py_atan2.
1548
1549
TESTS::
1550
1551
sage: from sage.symbolic.pynac import py_atan2_for_doctests
1552
sage: py_atan2_for_doctests(0., 1.)
1553
1.57079632679490
1554
"""
1555
return py_atan2(x, y)
1556
1557
cdef public object py_sinh(object x) except +:
1558
try:
1559
return x.sinh()
1560
except AttributeError:
1561
return RR(x).sinh()
1562
1563
1564
cdef public object py_cosh(object x) except +:
1565
if PY_TYPE_CHECK_EXACT(x, float):
1566
return math.cosh(x)
1567
try:
1568
return x.cosh()
1569
except AttributeError:
1570
return RR(x).cosh()
1571
1572
cdef public object py_tanh(object x) except +:
1573
try:
1574
return x.tanh()
1575
except AttributeError:
1576
return RR(x).tanh()
1577
1578
1579
cdef public object py_asinh(object x) except +:
1580
try:
1581
return x.arcsinh()
1582
except AttributeError:
1583
return CC(x).arcsinh()
1584
1585
cdef public object py_acosh(object x) except +:
1586
try:
1587
return x.arccosh()
1588
except AttributeError:
1589
pass
1590
try:
1591
return RR(x).arccosh()
1592
except TypeError:
1593
return CC(x).arccosh()
1594
1595
1596
cdef public object py_atanh(object x) except +:
1597
try:
1598
return x.arctanh()
1599
except AttributeError:
1600
return CC(x).arctanh()
1601
1602
cdef public object py_lgamma(object x) except +:
1603
"""
1604
Return the value of the log gamma function at the given value.
1605
1606
The value is expected to be a numerical object, in RR, CC, RDF or CDF.
1607
1608
EXAMPLES::
1609
1610
sage: from sage.symbolic.pynac import py_lgamma_for_doctests as py_lgamma
1611
sage: py_lgamma(4)
1612
1.79175946922805
1613
sage: py_lgamma(4.r)
1614
1.791759469228055
1615
sage: py_lgamma(4r)
1616
1.791759469228055
1617
sage: py_lgamma(CC.0)
1618
-0.650923199301856 - 1.87243664726243*I
1619
sage: py_lgamma(ComplexField(100).0)
1620
-0.65092319930185633888521683150 - 1.8724366472624298171188533494*I
1621
"""
1622
cdef gsl_sf_result lnr, arg
1623
cdef gsl_complex res
1624
if PY_TYPE_CHECK_EXACT(x, int) or PY_TYPE_CHECK_EXACT(x, long):
1625
x = float(x)
1626
if PY_TYPE_CHECK_EXACT(x, float):
1627
return sage_lgammal(x)
1628
elif PY_TYPE_CHECK_EXACT(x, complex):
1629
gsl_sf_lngamma_complex_e(PyComplex_RealAsDouble(x),PyComplex_ImagAsDouble(x), &lnr, &arg)
1630
res = gsl_complex_polar(lnr.val, arg.val)
1631
return PyComplex_FromDoubles(res.dat[0], res.dat[1])
1632
elif isinstance(x, Integer):
1633
return x.gamma().log().n()
1634
1635
# try / except blocks are faster than
1636
# if hasattr(x, 'log_gamma')
1637
try:
1638
return x.log_gamma()
1639
except AttributeError:
1640
pass
1641
1642
try:
1643
return x.gamma().log()
1644
except AttributeError:
1645
pass
1646
1647
return CC(x).gamma().log()
1648
1649
def py_lgamma_for_doctests(x):
1650
"""
1651
This function tests py_lgamma.
1652
1653
EXAMPLES::
1654
1655
sage: from sage.symbolic.pynac import py_lgamma_for_doctests
1656
sage: py_lgamma_for_doctests(CC(I))
1657
-0.650923199301856 - 1.87243664726243*I
1658
"""
1659
return py_lgamma(x)
1660
1661
cdef public object py_isqrt(object x) except +:
1662
return Integer(x).isqrt()
1663
1664
cdef public object py_sqrt(object x) except +:
1665
try:
1666
# WORRY: What if Integer's sqrt calls symbolic one and we go in circle?
1667
return x.sqrt()
1668
except AttributeError, msg:
1669
return sage_sqrtl(float(x))
1670
1671
cdef public object py_abs(object x) except +:
1672
return abs(x)
1673
1674
cdef public object py_mod(object x, object n) except +:
1675
"""
1676
Return x mod n. Both x and n are assumed to be integers.
1677
1678
EXAMPLES::
1679
1680
sage: from sage.symbolic.pynac import py_mod_for_doctests as py_mod
1681
sage: py_mod(I.parent(5), 4)
1682
1
1683
sage: py_mod(3, -2)
1684
-1
1685
sage: py_mod(3/2, 2)
1686
Traceback (most recent call last):
1687
...
1688
TypeError: no conversion of this rational to integer
1689
1690
1691
Note: The original code for this function in GiNaC checks if the arguments
1692
are integers, and returns 0 otherwise. We omit this check, since all the
1693
calls to py_mod are preceded by an integer check. We also raise an error
1694
if converting the arguments to integers fails, since silently returning 0
1695
would hide possible misuses of this function.
1696
1697
Regarding the sign of the return value, the CLN reference manual says:
1698
1699
If x and y are both >= 0, mod(x,y) = rem(x,y) >= 0. In general,
1700
mod(x,y) has the sign of y or is zero, and rem(x,y) has the sign of
1701
x or is zero.
1702
1703
This matches the behavior of the % operator for integers in Sage.
1704
"""
1705
return Integer(x) % Integer(n)
1706
1707
def py_mod_for_doctests(x, n):
1708
"""
1709
This function is a python wrapper so py_mod can be tested. The real tests
1710
are in the docstring for py_mod.
1711
1712
EXAMPLES::
1713
1714
sage: from sage.symbolic.pynac import py_mod_for_doctests
1715
sage: py_mod_for_doctests(5, 2)
1716
1
1717
"""
1718
return py_mod(x, n)
1719
1720
cdef public object py_smod(object a, object b) except +:
1721
# Modulus (in symmetric representation).
1722
# Equivalent to Maple's mods.
1723
# returns a mod b in the range [-iquo(abs(b)-1,2), iquo(abs(b),2)]
1724
a = Integer(a); b = Integer(b)
1725
b = abs(b)
1726
c = a % b
1727
if c > b//2:
1728
c -= b
1729
return c
1730
1731
cdef public object py_irem(object x, object n) except +:
1732
return Integer(x) % Integer(n)
1733
1734
cdef public object py_iquo(object x, object n) except +:
1735
return Integer(x)//Integer(n)
1736
1737
cdef public object py_iquo2(object x, object n) except +:
1738
x = Integer(x); n = Integer(n)
1739
try:
1740
q = x//n
1741
r = x - q*n
1742
return q, r
1743
except (TypeError, ValueError):
1744
return 0, 0
1745
1746
cdef public int py_int_length(object x) except -1:
1747
# Size in binary notation. For integers, this is the smallest n >= 0 such
1748
# that -2^n <= x < 2^n. If x > 0, this is the unique n > 0 such that
1749
# 2^(n-1) <= x < 2^n. This returns 0 if x is not an integer.
1750
return Integer(x).nbits()
1751
1752
from sage.structure.parent import Parent
1753
cdef public object py_li(object x, object n, object parent) except +:
1754
"""
1755
Returns a numerical approximation of polylog(n, x) with precision given
1756
by the ``parent`` argument.
1757
1758
EXAMPLES::
1759
1760
sage: from sage.symbolic.pynac import py_li_for_doctests as py_li
1761
sage: py_li(0,2,RR)
1762
0.000000000000000
1763
sage: py_li(-1,2,RR)
1764
-0.822467033424113
1765
sage: py_li(0, 1, float)
1766
0.000000000000000
1767
"""
1768
import mpmath
1769
if isinstance(parent, Parent) and hasattr(parent, 'prec'):
1770
prec = parent.prec()
1771
else:
1772
prec = 53
1773
return mpmath_utils.call(mpmath.polylog, n, x, prec=prec)
1774
1775
def py_li_for_doctests(x, n, parent):
1776
"""
1777
This function is a python wrapper so py_li can be tested. The real tests
1778
are in the docstring for py_li.
1779
1780
EXAMPLES::
1781
1782
sage: from sage.symbolic.pynac import py_li_for_doctests
1783
sage: py_li_for_doctests(0,2,float)
1784
0.000000000000000
1785
"""
1786
return py_li(x, n, parent)
1787
1788
cdef public object py_psi(object x) except +:
1789
"""
1790
EXAMPLES::
1791
1792
sage: from sage.symbolic.pynac import py_psi_for_doctests as py_psi
1793
sage: py_psi(0)
1794
Traceback (most recent call last):
1795
...
1796
ValueError: polygamma pole
1797
sage: py_psi(1)
1798
-0.577215664901533
1799
sage: euler_gamma.n()
1800
0.577215664901533
1801
"""
1802
import mpmath
1803
if PY_TYPE_CHECK(x, Element) and hasattr((<Element>x)._parent, 'prec'):
1804
prec = (<Element>x)._parent.prec()
1805
else:
1806
prec = 53
1807
return mpmath_utils.call(mpmath.psi, 0, x, prec=prec)
1808
1809
def py_psi_for_doctests(x):
1810
"""
1811
This function is a python wrapper so py_psi can be tested. The real tests
1812
are in the docstring for py_psi.
1813
1814
EXAMPLES::
1815
1816
sage: from sage.symbolic.pynac import py_psi_for_doctests
1817
sage: py_psi_for_doctests(2)
1818
0.422784335098467
1819
"""
1820
return py_psi(x)
1821
1822
cdef public object py_psi2(object n, object x) except +:
1823
"""
1824
EXAMPLES::
1825
1826
sage: from sage.symbolic.pynac import py_psi2_for_doctests as py_psi2
1827
sage: py_psi2(2, 1)
1828
-2.40411380631919
1829
"""
1830
import mpmath
1831
if PY_TYPE_CHECK(x, Element) and hasattr((<Element>x)._parent, 'prec'):
1832
prec = (<Element>x)._parent.prec()
1833
else:
1834
prec = 53
1835
return mpmath_utils.call(mpmath.psi, n, x, prec=prec)
1836
1837
def py_psi2_for_doctests(n, x):
1838
"""
1839
This function is a python wrapper so py_psi2 can be tested. The real tests
1840
are in the docstring for py_psi2.
1841
1842
EXAMPLES::
1843
1844
sage: from sage.symbolic.pynac import py_psi2_for_doctests
1845
sage: py_psi2_for_doctests(1, 2)
1846
0.644934066848226
1847
"""
1848
return py_psi2(n, x)
1849
1850
cdef public object py_li2(object x) except +:
1851
"""
1852
EXAMPLES::
1853
1854
sage: from sage.symbolic.pynac import py_li2_for_doctests as py_li2
1855
sage: py_li2(-1.1)
1856
-0.890838090262283
1857
"""
1858
import mpmath
1859
if PY_TYPE_CHECK(x, Element) and hasattr((<Element>x)._parent, 'prec'):
1860
prec = (<Element>x)._parent.prec()
1861
else:
1862
prec = 53
1863
return mpmath_utils.call(mpmath.polylog, 2, x, prec=prec)
1864
1865
1866
def py_li2_for_doctests(x):
1867
"""
1868
This function is a python wrapper so py_psi2 can be tested. The real tests
1869
are in the docstring for py_psi2.
1870
1871
EXAMPLES::
1872
1873
sage: from sage.symbolic.pynac import py_li2_for_doctests
1874
sage: py_li2_for_doctests(-1.1)
1875
-0.890838090262283
1876
"""
1877
return py_li2(x)
1878
1879
##################################################################
1880
# Constants
1881
##################################################################
1882
1883
cdef public GConstant py_get_constant(const_char_ptr name) except +:
1884
"""
1885
Returns a constant given its name. This is called by
1886
constant::unarchive in constant.cpp in Pynac and is used for
1887
pickling.
1888
"""
1889
from sage.symbolic.constants import constants_name_table
1890
cdef PynacConstant pc
1891
c = constants_name_table.get(name, None)
1892
if c is None:
1893
raise RuntimeError
1894
else:
1895
pc = c._pynac
1896
return pc.object
1897
1898
cdef public object py_eval_constant(unsigned serial, object parent) except +:
1899
from sage.symbolic.constants import constants_table
1900
constant = constants_table[serial]
1901
return parent(constant)
1902
1903
cdef public object py_eval_unsigned_infinity() except +:
1904
"""
1905
Returns unsigned_infinity.
1906
"""
1907
from sage.rings.infinity import unsigned_infinity
1908
return unsigned_infinity
1909
1910
def py_eval_unsigned_infinity_for_doctests():
1911
"""
1912
This function tests py_eval_unsigned_infinity.
1913
1914
TESTS::
1915
sage: from sage.symbolic.pynac import py_eval_unsigned_infinity_for_doctests as py_eval_unsigned_infinity
1916
sage: py_eval_unsigned_infinity()
1917
Infinity
1918
"""
1919
return py_eval_unsigned_infinity()
1920
1921
cdef public object py_eval_infinity() except +:
1922
"""
1923
Returns positive infinity, i.e., oo.
1924
"""
1925
from sage.rings.infinity import infinity
1926
return infinity
1927
1928
def py_eval_infinity_for_doctests():
1929
"""
1930
This function tests py_eval_infinity.
1931
1932
TESTS::
1933
sage: from sage.symbolic.pynac import py_eval_infinity_for_doctests as py_eval_infinity
1934
sage: py_eval_infinity()
1935
+Infinity
1936
"""
1937
return py_eval_infinity()
1938
1939
cdef public object py_eval_neg_infinity() except +:
1940
"""
1941
Returns minus_infinity.
1942
"""
1943
from sage.rings.infinity import minus_infinity
1944
return minus_infinity
1945
1946
def py_eval_neg_infinity_for_doctests():
1947
"""
1948
This function tests py_eval_neg_infinity.
1949
1950
TESTS::
1951
sage: from sage.symbolic.pynac import py_eval_neg_infinity_for_doctests as py_eval_neg_infinity
1952
sage: py_eval_neg_infinity()
1953
-Infinity
1954
"""
1955
return py_eval_neg_infinity()
1956
1957
##################################################################
1958
# Constructors
1959
##################################################################
1960
cdef Integer z = Integer(0)
1961
cdef public object py_integer_from_long(long x) except +:
1962
cdef Integer z = PY_NEW(Integer)
1963
mpz_init_set_si(z.value, x)
1964
return z
1965
1966
cdef public object py_integer_from_python_obj(object x) except +:
1967
return Integer(x)
1968
1969
1970
ZERO = ring.SR(0)
1971
ONE = ring.SR(1)
1972
ONE_HALF = ring.SR(Rational((1,2)))
1973
1974
symbol_table = {'functions':{}}
1975
def register_symbol(obj, conversions):
1976
"""
1977
Add an object to the symbol table, along with how to convert it to
1978
other systems such as Maxima, Mathematica, etc. This table is used
1979
to convert *from* other systems back to Sage.
1980
1981
INPUTS:
1982
1983
- `obj` -- a symbolic object or function.
1984
1985
- `conversions` -- a dictionary of conversions, where the keys
1986
are the names of interfaces (e.g.,
1987
'maxima'), and the values are the string
1988
representation of obj in that system.
1989
1990
1991
1992
EXAMPLES::
1993
1994
sage: sage.symbolic.pynac.register_symbol(SR(5),{'maxima':'five'})
1995
sage: SR(maxima_calculus('five'))
1996
5
1997
"""
1998
conversions = dict(conversions)
1999
try:
2000
conversions['sage'] = obj.name()
2001
except AttributeError:
2002
pass
2003
for system, value in conversions.iteritems():
2004
system_table = symbol_table.get(system, None)
2005
if system_table is None:
2006
symbol_table[system] = system_table = {}
2007
system_table[value] = obj
2008
2009
2010
2011
import sage.rings.integer
2012
ginac_pyinit_Integer(sage.rings.integer.Integer)
2013
2014
import sage.rings.real_double
2015
ginac_pyinit_Float(sage.rings.real_double.RDF)
2016
2017
cdef Element pynac_I
2018
I = None
2019
2020
def init_pynac_I():
2021
"""
2022
Initialize the numeric I object in pynac. We use the generator of QQ(i).
2023
2024
EXAMPLES::
2025
2026
sage: sage.symbolic.pynac.init_pynac_I()
2027
sage: type(sage.symbolic.pynac.I)
2028
<type 'sage.symbolic.expression.Expression'>
2029
sage: type(sage.symbolic.pynac.I.pyobject())
2030
<type 'sage.rings.number_field.number_field_element_quadratic.NumberFieldElement_quadratic'>
2031
"""
2032
global pynac_I, I
2033
from sage.rings.number_field.number_field import QuadraticField
2034
K = QuadraticField(-1, 'I', embedding=CC.gen(), latex_name='i')
2035
pynac_I = K.gen()
2036
ginac_pyinit_I(pynac_I)
2037
I = new_Expression_from_GEx(ring.SR, g_I)
2038
2039
2040
def init_function_table():
2041
"""
2042
Initializes the function pointer table in Pynac. This must be
2043
called before Pynac is used; otherwise, there will be segfaults.
2044
"""
2045
2046
py_funcs.py_binomial_int = &py_binomial_int
2047
py_funcs.py_binomial = &py_binomial
2048
py_funcs.py_gcd = &py_gcd
2049
py_funcs.py_lcm = &py_lcm
2050
py_funcs.py_real = &py_real
2051
py_funcs.py_imag = &py_imag
2052
py_funcs.py_numer = &py_numer
2053
py_funcs.py_denom = &py_denom
2054
py_funcs.py_conjugate = &py_conjugate
2055
2056
py_funcs.py_is_rational = &py_is_rational
2057
py_funcs.py_is_crational = &py_is_crational
2058
py_funcs.py_is_real = &py_is_real
2059
py_funcs.py_is_integer = &py_is_integer
2060
py_funcs.py_is_equal = &py_is_equal
2061
py_funcs.py_is_even = &py_is_even
2062
py_funcs.py_is_cinteger = &py_is_cinteger
2063
py_funcs.py_is_prime = &py_is_prime
2064
2065
py_funcs.py_integer_from_long = &py_integer_from_long
2066
py_funcs.py_integer_from_python_obj = &py_integer_from_python_obj
2067
2068
py_funcs.py_float = &py_float
2069
py_funcs.py_RDF_from_double = &py_RDF_from_double
2070
2071
py_funcs.py_factorial = &py_factorial
2072
py_funcs.py_doublefactorial = &py_doublefactorial
2073
py_funcs.py_fibonacci = &py_fibonacci
2074
py_funcs.py_step = &py_step
2075
py_funcs.py_bernoulli = &py_bernoulli
2076
py_funcs.py_sin = &py_sin
2077
py_funcs.py_cos = &py_cos
2078
py_funcs.py_zeta = &py_zeta
2079
py_funcs.py_exp = &py_exp
2080
py_funcs.py_log = &py_log
2081
py_funcs.py_tan = &py_tan
2082
py_funcs.py_asin = &py_asin
2083
py_funcs.py_acos = &py_acos
2084
py_funcs.py_atan = &py_atan
2085
py_funcs.py_atan2 = &py_atan2
2086
py_funcs.py_sinh = &py_sinh
2087
py_funcs.py_cosh = &py_cosh
2088
py_funcs.py_tanh = &py_tanh
2089
py_funcs.py_asinh = &py_asinh
2090
py_funcs.py_acosh = &py_acosh
2091
py_funcs.py_atanh = &py_atanh
2092
py_funcs.py_tgamma = &py_tgamma
2093
py_funcs.py_lgamma = &py_lgamma
2094
py_funcs.py_isqrt = &py_isqrt
2095
py_funcs.py_sqrt = &py_sqrt
2096
py_funcs.py_abs = &py_abs
2097
py_funcs.py_mod = &py_mod
2098
py_funcs.py_smod = &py_smod
2099
py_funcs.py_irem = &py_irem
2100
py_funcs.py_iquo = &py_iquo
2101
py_funcs.py_iquo2 = &py_iquo2
2102
py_funcs.py_li = &py_li
2103
py_funcs.py_li2 = &py_li2
2104
py_funcs.py_psi = &py_psi
2105
py_funcs.py_psi2 = &py_psi2
2106
2107
py_funcs.py_int_length = &py_int_length
2108
2109
py_funcs.py_eval_constant = &py_eval_constant
2110
py_funcs.py_eval_unsigned_infinity = &py_eval_unsigned_infinity
2111
py_funcs.py_eval_infinity = &py_eval_infinity
2112
py_funcs.py_eval_neg_infinity = &py_eval_neg_infinity
2113
2114
py_funcs.py_get_parent_char = &py_get_parent_char
2115
2116
py_funcs.py_latex = &py_latex
2117
py_funcs.py_repr = &py_repr
2118
2119
py_funcs.py_dumps = &py_dumps
2120
py_funcs.py_loads = &py_loads
2121
2122
py_funcs.exvector_to_PyTuple = &exvector_to_PyTuple
2123
py_funcs.pyExpression_to_ex = &pyExpression_to_ex
2124
py_funcs.ex_to_pyExpression = &ex_to_pyExpression
2125
py_funcs.py_print_function = &py_print_function
2126
py_funcs.py_latex_function = &py_latex_function
2127
py_funcs.py_get_ginac_serial = &py_get_ginac_serial
2128
py_funcs.py_get_sfunction_from_serial = &py_get_sfunction_from_serial
2129
py_funcs.py_get_serial_from_sfunction = &py_get_serial_from_sfunction
2130
py_funcs.py_get_serial_for_new_sfunction = &py_get_serial_for_new_sfunction
2131
2132
py_funcs.py_get_constant = &py_get_constant
2133
py_funcs.py_print_fderivative = &py_print_fderivative
2134
py_funcs.py_latex_fderivative = &py_latex_fderivative
2135
py_funcs.paramset_to_PyTuple = &paramset_to_PyTuple
2136
py_funcs.py_rational_power_parts = &py_rational_power_parts
2137
2138
init_function_table()
2139
init_pynac_I()
2140
2141
"""
2142
Some tests for the formal square root of -1.
2143
2144
EXAMPLES::
2145
2146
sage: I
2147
I
2148
sage: I^2
2149
-1
2150
2151
Note that conversions to real fields will give TypeErrors::
2152
2153
sage: float(I)
2154
Traceback (most recent call last):
2155
...
2156
TypeError: unable to simplify to float approximation
2157
sage: gp(I)
2158
I
2159
sage: RR(I)
2160
Traceback (most recent call last):
2161
...
2162
TypeError: Unable to convert x (='1.00000000000000*I') to real number.
2163
2164
We can convert to complex fields::
2165
2166
sage: C = ComplexField(200); C
2167
Complex Field with 200 bits of precision
2168
sage: C(I)
2169
1.0000000000000000000000000000000000000000000000000000000000*I
2170
sage: I._complex_mpfr_field_(ComplexField(53))
2171
1.00000000000000*I
2172
2173
sage: I._complex_double_(CDF)
2174
1.0*I
2175
sage: CDF(I)
2176
1.0*I
2177
2178
sage: z = I + I; z
2179
2*I
2180
sage: C(z)
2181
2.0000000000000000000000000000000000000000000000000000000000*I
2182
sage: 1e8*I
2183
1.00000000000000e8*I
2184
2185
sage: complex(I)
2186
1j
2187
2188
sage: QQbar(I)
2189
1*I
2190
2191
sage: abs(I)
2192
1
2193
2194
sage: I.minpoly()
2195
x^2 + 1
2196
sage: maxima(2*I)
2197
2*%i
2198
2199
TESTS::
2200
2201
sage: repr(I)
2202
'I'
2203
sage: latex(I)
2204
i
2205
"""
2206
2207
2208
set_ginac_fn_serial()
2209
2210