Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/calculus/var.pyx
4057 views
1
from sage.symbolic.function_factory import function as new_function
2
from sage.symbolic.ring import SR
3
4
def var(*args, **kwds):
5
r"""
6
Create a symbolic variable with the name *s*.
7
8
INPUT:
9
10
- ``args`` - A single string ``var('x y')``, a list of strings
11
``var(['x','y'])``, or multiple strings ``var('x', 'y')``. A
12
single string can be either a single variable name, or a space
13
or comma separated list of variable names. In a list or tuple of
14
strings, each entry is one variable. If multiple arguments are
15
specified, each argument is taken to be one variable. Spaces
16
before or after variable names are ignored.
17
18
- ``kwds`` - keyword arguments can be given to specify domain and
19
custom latex_name for variables. See EXAMPLES for usage.
20
21
.. note::
22
23
The new variable is both returned and automatically injected
24
into the global namespace. If you need symbolic variable in
25
library code, it is better to use either SR.var() or SR.symbol().
26
27
OUTPUT:
28
29
If a single symbolic variable was created, the variable
30
itself. Otherwise, a tuple of symbolic variables. The variable
31
names are checked to be valid Python identifiers and a
32
``ValueError`` is raised otherwise.
33
34
EXAMPLES:
35
36
Here are the different ways to define three variables ``x``, ``y``,
37
and ``z`` in a single line::
38
39
sage: var('x y z')
40
(x, y, z)
41
sage: var('x, y, z')
42
(x, y, z)
43
sage: var(['x', 'y', 'z'])
44
(x, y, z)
45
sage: var('x', 'y', 'z')
46
(x, y, z)
47
sage: var('x'), var('y'), var(z)
48
(x, y, z)
49
50
We define some symbolic variables::
51
52
sage: var('n xx yy zz')
53
(n, xx, yy, zz)
54
55
Then we make an algebraic expression out of them::
56
57
sage: f = xx^n + yy^n + zz^n; f
58
xx^n + yy^n + zz^n
59
60
By default, var returns a complex variable. To define real or positive
61
variables we can specify the domain as::
62
63
sage: x = var('x', domain=RR); x; x.conjugate()
64
x
65
x
66
sage: y = var('y', domain='real'); y.conjugate()
67
y
68
sage: y = var('y', domain='positive'); y.abs()
69
y
70
71
Custom latex expression can be assigned to variable::
72
73
sage: x = var('sui', latex_name="s_{u,i}"); x._latex_()
74
's_{u,i}'
75
76
In notebook, we can also colorize latex expression::
77
78
sage: x = var('sui', latex_name="\\color{red}{s_{u,i}}"); x._latex_()
79
'\\color{red}{s_{u,i}}'
80
81
We can substitute a new variable name for n::
82
83
sage: f(n = var('sigma'))
84
xx^sigma + yy^sigma + zz^sigma
85
86
If you make an important built-in variable into a symbolic variable,
87
you can get back the original value using restore::
88
89
sage: var('QQ RR')
90
(QQ, RR)
91
sage: QQ
92
QQ
93
sage: restore('QQ')
94
sage: QQ
95
Rational Field
96
97
We make two new variables separated by commas::
98
99
sage: var('theta, gamma')
100
(theta, gamma)
101
sage: theta^2 + gamma^3
102
gamma^3 + theta^2
103
104
The new variables are of type Expression, and belong
105
to the symbolic expression ring::
106
107
sage: type(theta)
108
<type 'sage.symbolic.expression.Expression'>
109
sage: parent(theta)
110
Symbolic Ring
111
112
TESTS::
113
114
sage: var('q',ns=False)
115
Traceback (most recent call last):
116
...
117
NotImplementedError: The new (Pynac) symbolics are now the only symbolics; please do not use keyword `ns` any longer.
118
sage: q
119
Traceback (most recent call last):
120
...
121
NameError: name 'q' is not defined
122
sage: var('q',ns=1)
123
doctest:...: DeprecationWarning: The new (Pynac) symbolics are now the only symbolics; please do not use keyword 'ns' any longer.
124
q
125
"""
126
if len(args)==1:
127
name = args[0]
128
else:
129
name = args
130
G = globals() # this is the reason the code must be in Cython.
131
if kwds.has_key('ns'):
132
if kwds['ns']:
133
from sage.misc.misc import deprecation
134
deprecation("The new (Pynac) symbolics are now the only symbolics; please do not use keyword 'ns' any longer.")
135
else:
136
raise NotImplementedError, "The new (Pynac) symbolics are now the only symbolics; please do not use keyword `ns` any longer."
137
kwds.pop('ns')
138
v = SR.var(name, **kwds)
139
if isinstance(v, tuple):
140
for x in v:
141
G[repr(x)] = x
142
else:
143
G[repr(v)] = v
144
return v
145
146
def function(s, *args, **kwds):
147
r"""
148
Create a formal symbolic function with the name *s*.
149
150
INPUT:
151
152
- ``s`` - a string, either a single variable name, or a space or
153
comma separated list of variable names.
154
155
- ``**kwds`` - keyword arguments. Either one of the following two
156
keywords can be used to customize latex representation of
157
symbolic functions:
158
159
(1) latex_name=LaTeX
160
where ``LaTeX`` is any valid latex expression.
161
Ex: f = function('f', x, latex_name="\\mathcal{F}")
162
See EXAMPLES for more.
163
164
(2) print_latex_func=my_latex_print
165
where ``my_latex_print`` is any callable function
166
that returns a valid latex expression.
167
Ex: f = function('f', x, print_latex_func=my_latex_print)
168
See EXAMPLES for an explicit usage.
169
170
.. note::
171
172
The new function is both returned and automatically injected
173
into the global namespace. If you use this function in library
174
code, it is better to use sage.symbolic.function_factory.function,
175
since it won't touch the global namespace.
176
177
EXAMPLES::
178
179
We create a formal function called supersin::
180
181
sage: f = function('supersin', x)
182
sage: f
183
supersin(x)
184
185
We can immediately use supersin in symbolic expressions::
186
187
sage: y, z, A = var('y z A')
188
sage: supersin(y+z) + A^3
189
A^3 + supersin(y + z)
190
191
We can define other functions in terms of supersin::
192
193
sage: g(x,y) = supersin(x)^2 + sin(y/2)
194
sage: g
195
(x, y) |--> supersin(x)^2 + sin(1/2*y)
196
sage: g.diff(y)
197
(x, y) |--> 1/2*cos(1/2*y)
198
sage: k = g.diff(x); k
199
(x, y) |--> 2*supersin(x)*D[0](supersin)(x)
200
201
Custom typesetting of symbolic functions in LaTeX::
202
203
(1) Either using latex_name keyword::
204
205
sage: riemann(x) = function('riemann', x, latex_name="\\mathcal{R}")
206
sage: latex(riemann(x))
207
\mathcal{R}\left(x\right)
208
209
(2) Or passing a custom callable function that returns a
210
latex expression::
211
212
sage: mu,nu = var('mu,nu')
213
sage: def my_latex_print(self, *args): return "\\psi_{%s}"%(', '.join(map(latex, args)))
214
sage: psi(mu,nu) = function('psi', mu, nu, print_latex_func=my_latex_print)
215
sage: latex(psi(mu,nu))
216
\psi_{\mu, \nu}
217
218
In Sage 4.0, you must now use the :meth:`substitute_function`
219
method to replace functions::
220
221
sage: k.substitute_function(supersin, sin)
222
2*sin(x)*cos(x)
223
"""
224
if len(args) > 0:
225
return function(s, **kwds)(*args)
226
227
G = globals() # this is the reason the code must be in Cython.
228
v = new_function(s, **kwds)
229
if isinstance(v, tuple):
230
for x in v:
231
G[repr(x)] = x
232
else:
233
G[repr(v)] = v
234
return v
235
236
237
def clear_vars():
238
"""
239
Delete all 1-letter symbolic variables that are predefined at
240
startup of Sage. Any one-letter global variables that are not
241
symbolic variables are not cleared.
242
243
EXAMPLES::
244
245
sage: var('x y z')
246
(x, y, z)
247
sage: (x+y)^z
248
(x + y)^z
249
sage: k = 15
250
sage: clear_vars()
251
sage: (x+y)^z
252
Traceback (most recent call last):
253
...
254
NameError: name 'x' is not defined
255
sage: expand((e + i)^2)
256
2*I*e + e^2 - 1
257
sage: k
258
15
259
"""
260
G = globals()
261
from sage.symbolic.ring import is_SymbolicVariable
262
for i in range(65,65+26) + range(97,97+26):
263
if G.has_key(chr(i)) and is_SymbolicVariable(G[chr(i)]):
264
# We check to see if there is a corresponding pyobject
265
# associated with the expression. This will work for
266
# constants which we want to keep, but will fail for
267
# variables that we want to delete.
268
try:
269
G[chr(i)].pyobject()
270
except TypeError:
271
del G[chr(i)]
272
273
274
275
276