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