Last active
August 16, 2022 04:43
-
-
Save fdzuluaga2020/eb4722866eab6a8595cbbfcfb270639e to your computer and use it in GitHub Desktop.
SageMath
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Definicion de la Funcion : | |
f(x)=x^3+1 | |
f(2) | |
9 | |
show(f) | |
------------------------------------------ | |
What is the limit of this function as x approaches 1? | |
lim(f,x=1) | |
x |--> 2 | |
------------------------------------------ | |
Since a limit may exist even if the function is not defined, Sage uses the syntax x=1 to show the input value approached in all situations. | |
lim((x^2-1)/(x-1),x=1) | |
2 | |
------------------------------------------ | |
Next, we’ll return to the original function, and check the two directional limits. | |
The syntax uses the extra keyword dir. | |
Notice that we use dir='right', not dir=right. | |
It’s also okay to use dir='+', like we use dir='-' below. | |
This is basically because otherwise we might have done something like let right=55 earlier, so instead Sage - and Python - requires us to put 'right' and '-' in quotes to make it clear they are not variables. | |
lim(f,x=1,dir='-'); lim(f,x=1,dir='right'); f(1) | |
x |--> 2 | |
x |--> 2 | |
2 | |
------------------------------------------ | |
For example, here are three ways to get the basic, single-variable derivative of f(x)=x3+1. | |
diff(f,x); derivative(f,x); f.derivative(x) | |
x |--> 3*x^2 | |
x |--> 3*x^2 | |
x |--> 3*x^2 | |
------------------------------------------ | |
derivative(sinh(x^2+sqrt(x-1)),x) | |
1/2*(4*x + 1/sqrt(x - 1))*cosh(x^2 + sqrt(x - 1)) | |
show(derivative(sinh(x^2+sqrt(x-1)),x,3)) | |
------------------------------------------ | |
The syntax for indefinite integration is similar to that for differentiation. | |
integral(cos(x),x) | |
sin(x) | |
------------------------------------------ | |
Definite integration has similar syntax to plotting. | |
integral(cos(x),(x,0,pi/2)) | |
1 | |
------------------------------------------ | |
h(x)=sec(x) | |
h.integrate(x) | |
x |--> log(sec(x) + tan(x)) | |
integrate(sec(x),x) | |
log(sec(x) + tan(x)) | |
integrate(1/(1+x^5),x) | |
1/5*sqrt(5)*(sqrt(5) + 1)*arctan((4*x + sqrt(5) - 1)/sqrt(2*sqrt(5) + 10))/sqrt(2*sqrt(5) + 10) | |
+ 1/5*sqrt(5)*(sqrt(5) - 1)*arctan((4*x - sqrt(5) - 1)/sqrt(-2*sqrt(5) + 10))/sqrt(-2*sqrt(5) + 10) | |
- 1/10*(sqrt(5) + 3)*log(2*x^2 - x*(sqrt(5) + 1) + 2)/(sqrt(5) + 1) | |
- 1/10*(sqrt(5) - 3)*log(2*x^2 + x*(sqrt(5) - 1) + 2)/(sqrt(5) - 1) | |
+ 1/5*log(x + 1) | |
integral(1/(1+x^10),x) | |
...1/20*(sqrt(5) + 1)*arctan((4*x + sqrt(-2*sqrt(5) + 10))/(sqrt(5) + 1)) | |
+ 1/20*(sqrt(5) + 1)*arctan((4*x - sqrt(-2*sqrt(5) + 10))/(sqrt(5) + 1)) | |
+ 1/20*(sqrt(5) - 1)*arctan((4*x + sqrt(2*sqrt(5) + 10))/(sqrt(5) - 1)) | |
+ 1/20*(sqrt(5) - 1)*arctan((4*x - sqrt(2*sqrt(5) + 10))/(sqrt(5) - 1)) | |
+ 1/40*sqrt(2*sqrt(5) + 10)*log(x^2 + 1/2*x*sqrt(2*sqrt(5) + 10) + 1) | |
- 1/40*sqrt(2*sqrt(5) + 10)*log(x^2 - 1/2*x*sqrt(2*sqrt(5) + 10) + 1) | |
+ 1/40*sqrt(-2*sqrt(5) + 10)*log(x^2 + 1/2*x*sqrt(-2*sqrt(5) + 10) + 1) | |
- 1/40*sqrt(-2*sqrt(5) + 10)*log(x^2 - 1/2*x*sqrt(-2*sqrt(5) + 10) + 1) | |
+ 1/5*arctan(x) | |
------------------------------------------ | |
It is possible to be completely symbolic in doing integration. If you do this, you’ll have to make sure you define anything that’s a symbolic variable - which includes constants, naturally. | |
var('a,b') | |
(a, b) | |
integral(cos(x),(x,a,b)) | |
-sin(a) + sin(b) | |
------------------------------------------ | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Funciona como la lista, solo que puede ser indexada con cualquier objeto | |
d = {'hi':-2, 3/8:pi, e:pi} | |
d['hi'] | |
-2 | |
d[e] | |
pi | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
La Estructura mas simple es la lista : | |
list(range(2,10)) | |
[2, 3, 4, 5, 6, 7, 8, 9] | |
v = [1, "hello", 2/3, sin(x^3)] | |
v | |
[1, 'hello', 2/3, sin(x^3)] | |
------------------------------------------ | |
Las listas son en base 0 : | |
v[0] | |
1 | |
v[3] | |
sin(x^3) | |
------------------------------------------ | |
La cantidad de elementos de la lista se obtiene con len() | |
Se pueden agregar elementos a la lista con append | |
Se pueden eliminar elementos de la lista con del | |
len(v) | |
4 | |
v.append(1.5) | |
v | |
[1, 'hello', 2/3, sin(x^3), 1.50000000000000] | |
del v[1] | |
v | |
[1, 2/3, sin(x^3), 1.50000000000000] | |
------------------------------------------ | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Derivadas simples : | |
u = var('u') | |
diff(sin(u), u) | |
cos(u) | |
------------------------------------------ | |
Calculando Cuarta Derivada : | |
diff(sin(x^2), x, 4) | |
16*x^4*sin(x^2) - 48*x^2*cos(x^2) - 12*sin(x^2) | |
------------------------------------------ | |
Derivadas Parciales : | |
x, y = var('x,y') | |
f = x^2 + 17*y^2 | |
f.diff(x) | |
2*x | |
f.diff(y) | |
34*y | |
------------------------------------------ | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://doc.sagemath.org/html/en/index.html |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Ecuaciones Diferenciales Ordinarias : | |
t = var('t') # define a variable t | |
x = function('x')(t) # define x to be a function of that variable | |
DE = diff(x, t) + x - 1 | |
desolve(DE, [x,t]) | |
(_C + e^t)*e^(-t) | |
------------------------------------------ | |
Transformadas de Laplace : | |
s = var("s") | |
t = var("t") | |
f = t^2*exp(t) - sin(t) | |
f.laplace(t,s) | |
-1/(s^2 + 1) + 2/(s - 1)^3 | |
------------------------------------------ | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Par los for se usa el concepto de range : | |
------------------------------------------ | |
for(i=0; i<3; i++) se escribiria como : | |
for i in range(3): | |
print(i) | |
0 | |
1 | |
2 | |
------------------------------------------ | |
for(i=2;i<5;i++) se escribiria como : | |
for i in range(2,5): | |
print(i) | |
2 | |
3 | |
4 | |
------------------------------------------ | |
for(i=1;i<6;i+=2) se escribiria como : | |
for i in range(1,6,2): | |
print(i) | |
1 | |
3 | |
5 | |
------------------------------------------ | |
Para construir una tabla sencilla : | |
for i in range(5): | |
print('%6s %6s %6s' % (i, i^2, i^3)) | |
0 0 0 | |
1 1 1 | |
2 4 8 | |
3 9 27 | |
4 16 64 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
f = 1/((1+x)*(x-1)) | |
f.partial_fraction(x) | |
-1/2/(x + 1) + 1/2/(x - 1) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Para la definicion de funciones uso el comando def y termino los argumentos con : , el bloque de codigo es indentado automaticamente : | |
Se introduce la primera linea, se le da Enter y el genera la indentacion del bloque. | |
El bloque de codigo termina dandole Enter a la ultima linea para que se genere una linea en blanco | |
def is_even(n): | |
return n%2 == 0 | |
is_even(2) | |
True | |
Las funciones se pueden definir con argumentos opcionales : | |
def is_divisible_by(number, divisor=2): | |
return number%divisor == 0 | |
is_divisible_by(6) | |
True | |
is_divisible_by(6, 5) | |
False | |
La indentacion debe ser exacta en los bloques de codigo o sino se produce un error : | |
Mala Indentacion : | |
def even(n): | |
v = [] | |
for i in range(3,n): | |
if i % 2 == 0: | |
v.append(i) | |
return v | |
Indentacion Correcta : | |
ef even(n): | |
v = [] | |
for i in range(3,n): | |
if i % 2 == 0: | |
v.append(i) | |
return v | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Indefinidas : | |
integral(x*sin(x^2), x) | |
-1/2*cos(x^2) | |
------------------------------------------ | |
Definidas : | |
integral(x/(x^2+1), x, 0, 1) | |
1/2*log(2) | |
------------------------------------------ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Creation of matrices and matrix multiplication is easy and natural: | |
A = Matrix([[1,2,3],[3,2,1],[1,1,1]]) | |
w = vector([1,1,-4]) | |
w*A | |
(0, 0, 0) | |
A*w | |
(-9, 1, -2) | |
kernel(A) | |
Note that in Sage, the kernel of a matrix A is the “left kernel”, i.e. the space of vectors w such that wA=0. | |
------------------------------------------ | |
Solving matrix equations is easy, using the method solve_right. Evaluating A.solve_right(Y) returns a matrix (or vector) X so that AX=Y: | |
Y = vector([0, -4, -1]) | |
X = A.solve_right(Y) | |
X | |
(-2, 1, 0) | |
A * X # checking our answer... | |
(0, -4, -1) | |
A backslash \ can be used in the place of solve_right; use A \ Y instead of A.solve_right(Y). | |
A \ Y | |
(-2, 1, 0) | |
Similarly, use A.solve_left(Y) to solve for X in XA=Y | |
------------------------------------------ | |
Sage can also compute eigenvalues and eigenvectors: | |
A = matrix([[0, 4], [-1, 0]]) | |
A.eigenvalues () | |
[-2*I, 2*I] | |
B = matrix([[1, 3], [3, 1]]) | |
B.eigenvectors_left() | |
[(4, [ | |
(1, 1) | |
], 1), (-2, [ | |
(1, -1) | |
], 1)] | |
------------------------------------------ | |
As noted in Basic Rings, the ring over which a matrix is defined affects some of its properties. In the following, the first argument to the matrix command tells Sage to view the matrix as a matrix of integers (the ZZ case), a matrix of rational numbers (QQ), or a matrix of reals (RR): | |
AZ = matrix(ZZ, [[2,0], [0,1]]) | |
AQ = matrix(QQ, [[2,0], [0,1]]) | |
AR = matrix(RR, [[2,0], [0,1]]) | |
AZ.echelon_form() | |
[2 0] | |
[0 1] | |
AQ.echelon_form() | |
[1 0] | |
[0 1] | |
AR.echelon_form() | |
[ 1.00000000000000 0.000000000000000] | |
[0.000000000000000 1.00000000000000] | |
------------------------------------------ | |
For computing eigenvalues and eigenvectors of matrices over floating point real or complex numbers, the matrix should be defined over RDF (Real Double Field) or CDF (Complex Double Field), respectively. If no ring is specified and floating point real or complex numbers are used then by default the matrix is defined over the RR or CC fields, respectively, which do not support these computations for all the cases: | |
ARDF = matrix(RDF, [[1.2, 2], [2, 3]]) | |
ARDF.eigenvalues() # rel tol 8e-16 | |
[-0.09317121994613098, 4.293171219946131] | |
ACDF = matrix(CDF, [[1.2, I], [2, 3]]) | |
ACDF.eigenvectors_right() # rel tol 3e-15 | |
[(0.8818456983293743 - 0.8209140653434135*I, [(0.7505608183809549, -0.616145932704589 + 0.2387941530333261*I)], 1), | |
(3.3181543016706256 + 0.8209140653434133*I, [(0.14559469829270957 + 0.3756690858502104*I, 0.9152458258662108)], 1)] | |
------------------------------------------ | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://doc.sagemath.org/html/en/reference/numerical/index.html | |
There are bad news coming along with this definition of linear programming: an LP can be solved in polynomial time. This is indeed bad news, because this would mean that unless we define LP of exponential size, we cannot expect LP to solve NP-complete problems, which would be a disappointment. On a brighter side, it becomes NP-complete to solve a linear program if we are allowed to specify constraints of a different kind: requiring that some variables be integers instead of real values. Such an LP is actually called a “mixed integer linear program” (some variables can be integers, some other reals). Hence, we can expect to find in the MILP framework a wide range of expressivity. | |
The MILP class in Sage represents a MILP! It is also used to solve regular LP. It has a very small number of methods, meant to define our set of constraints and variables, then to read the solution found by the solvers once computed. It is also possible to export a MILP defined with Sage to a .lp or .mps file, understood by most solvers. | |
Let us ask Sage to solve the following LP: | |
Max: x+y+3z | |
Such that: x+2y≤45 | |
z−y≤8 | |
x,y,z≥0 | |
To achieve it, we need to define a corresponding MILP object, along with 3 variables x, y and z: | |
p = MixedIntegerLinearProgram() | |
v = p.new_variable(real=True, nonnegative=True) | |
x, y, z = v['x'], v['y'], v['z'] | |
Next, we set the objective function | |
p.set_objective(x + y + 3*z) | |
And finally we set the constraints | |
p.add_constraint(x + 2*y <= 4) | |
p.add_constraint(5*z - y <= 8) | |
The solve method returns by default the optimal value reached by the objective function | |
round(p.solve(), 2) | |
8.8 | |
We can read the optimal assignment found by the solver for x, y and z through the get_values method | |
round(p.get_values(x), 2) | |
4.0 | |
round(p.get_values(y), 2) | |
0.0 | |
round(p.get_values(z), 2) | |
1.6 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Existen tres tipos de celdas : | |
Code Cells : son las celdas en donde se introducen los calculos, recordar que son multi linea y se ejecutan con Shift + Enter | |
Markdown Cells : son las celdas utilizadas para trabajar con texto formateado bajo la modalidad de Markdown | |
Raw Cells : estas celdas no se evaluan y pueden ser utilizadas con Latex | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Evaluacion de Celdas : Shift + Enter | |
------------------------------------------ | |
La asignacion se hace con = | |
Los operadores de comparacion son <,>,== | |
------------------------------------------ | |
Potencias : 2^3 o 2**3 | |
------------------------------------------ | |
Modulo de la Division : 10%3 = 1 --> El modulo de la division es el restante de la division entera, asi 10 - 3*3 = 9 | |
Division Entera : 10//4=2 --> Retorna la parte entera de la division | |
------------------------------------------ | |
Raiz Cuadrada : sqrt(25) | |
------------------------------------------ | |
Numero de Digitos deseados : Sage siempre retorna valores exactos a no ser que se le defina el tipo de precision o aproximacion deseada | |
sin(10).n(digits=5) = -0.54402 | |
N(sin(10),digits=10) = -0.5440211109 | |
numerical_approx(pi, prec=200) = 3.1415926535897932384626433832795028841971693993751058209749 | |
sqrt(pi).numerical_approx() = 1.77245385090552 | |
exp(2) = e^2 | |
n(exp(2)) = 7.38905609893065 | |
------------------------------------------ | |
Si deseo obtener ayuda acerca de un comando simplemente digito ? al final, asi para tener ayuda acerca de la funcion tan --> tan? | |
------------------------------------------ | |
Se puedes definir multiples instrucciones en la misma linea separandolas por ; | |
a = 5; b = a + 3; c = b^2; c | |
64 | |
------------------------------------------ | |
Una linea de codigo tambien se puede expandir en varias lineas con el operador \ : | |
2 + \ | |
3 | |
5 | |
------------------------------------------ | |
Se pueden introducir multiples instrucciones en la misma celda, simplemente se le da Enter despues de cada linea y se ejecuta con Shift Enter : | |
x = var('x') | |
p1 = parametric_plot((cos(x),sin(x)),(x,0,2*pi),rgbcolor=hue(0.2)) | |
p2 = parametric_plot((cos(x),sin(x)^2),(x,0,2*pi),rgbcolor=hue(0.4)) | |
p3 = parametric_plot((cos(x),sin(x)^3),(x,0,2*pi),rgbcolor=hue(0.6)) | |
show(p1+p2+p3, axes=false) | |
------------------------------------------ | |
Se puede comentar cada linea con el operador # al final de cada linea de codigo | |
------------------------------------------ | |
Para visualizar los resultados en forma simbolica simplemente se usa la expresion show() | |
Adentro del parentesis va la operacion que se esta evaluando y cuyo resultado se quiere ver simbolicamente | |
show (integrate(1/sqrt(tan(x)),x)) | |
------------------------------------------ | |
Auto Complete : | |
Digitando las iniciales de un comando podemos presionar Tab para que el sistema nos sugiera los comandos que pudieran ejecutarse con esas iniciales |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://doc.sagemath.org/html/en/reference/plotting/index.html | |
Bidimensionales : | |
This command produces a yellow circle of radius 1, centered at the origin: | |
circle((0,0), 1, rgbcolor=(1,1,0)) | |
------------------------------------------ | |
You can also produce a filled circle: | |
circle((0,0), 1, rgbcolor=(1,1,0), fill=True) | |
------------------------------------------ | |
You can also create a circle by assigning it to a variable; this does not plot it: | |
c = circle((0,0), 1, rgbcolor=(1,1,0)) | |
To plot it, use c.show() or show(c), as follows: | |
c.show() | |
------------------------------------------ | |
Alternatively, evaluating c.save('filename.png') will save the plot to the given file. | |
Now, these ‘circles’ look more like ellipses because the axes are scaled differently. You can fix this: | |
c.show(aspect_ratio=1) | |
The command show(c, aspect_ratio=1) accomplishes the same thing, or you can save the picture using c.save('filename.png', aspect_ratio=1). | |
------------------------------------------ | |
Graficando Funciones : | |
plot(cos, (-5,5)) | |
------------------------------------------ | |
It’s important to notice that the axes of the plots will only intersect if the origin is in the viewing range of the graph, and that with sufficiently large values scientific notation may be used: | |
plot(x^2,(x,300,500)) | |
------------------------------------------ | |
You can combine several plots by adding them: | |
x = var('x') | |
p1 = parametric_plot((cos(x),sin(x)),(x,0,2*pi),rgbcolor=hue(0.2)) | |
p2 = parametric_plot((cos(x),sin(x)^2),(x,0,2*pi),rgbcolor=hue(0.4)) | |
p3 = parametric_plot((cos(x),sin(x)^3),(x,0,2*pi),rgbcolor=hue(0.6)) | |
show(p1+p2+p3, axes=false) | |
------------------------------------------ | |
Graficos de Contorno : | |
f = lambda x,y: cos(x*y) | |
contour_plot(f, (-4, 4), (-4, 4)) | |
------------------------------------------ | |
We draw a curve: | |
plot(x^2, (x,0,5)) | |
------------------------------------------ | |
We can add a graphics object to another one as an inset: | |
g1 = plot(x^2*sin(1/x), (x, -2, 2), axes_labels=['$x$', '$y$']) | |
g2 = plot(x^2*sin(1/x), (x, -0.3, 0.3), axes_labels=['$x$', '$y$'], | |
frame=True) | |
g1.inset(g2, pos=(0.15, 0.7, 0.25, 0.25)) | |
------------------------------------------ | |
Symbolline: | |
y(x) = x*sin(x^2) | |
v = [(x, y(x)) for x in [-3,-2.95,..,3]] | |
show(points(v, rgbcolor=(0.2,0.6, 0.1), pointsize=30) + plot(spline(v), -3.1, 3)) | |
------------------------------------------ | |
Cycliclink: | |
g1 = plot(cos(20*x)*exp(-2*x), 0, 1) | |
g2 = plot(2*exp(-30*x) - exp(-3*x), 0, 1) | |
show(graphics_array([g1, g2], 2, 1)) | |
------------------------------------------ | |
Pi Axis: | |
g1 = plot(sin(x), 0, 2*pi) | |
g2 = plot(cos(x), 0, 2*pi, linestyle="--") | |
(g1+g2).show(ticks=pi/6, tick_formatter=pi) # long time # show their sum, nicely formatted | |
------------------------------------------ | |
An illustration of integration: | |
f(x) = (x-3)*(x-5)*(x-7)+40 | |
P = line([(2,0),(2,f(2))], color='black') | |
P += line([(8,0),(8,f(8))], color='black') | |
P += polygon([(2,0),(2,f(2))] + [(x, f(x)) for x in [2,2.1,..,8]] + [(8,0),(2,0)], rgbcolor=(0.8,0.8,0.8),aspect_ratio='automatic') | |
P += text("$\\int_{a}^b f(x) dx$", (5, 20), fontsize=16, color='black') | |
P += plot(f, (1, 8.5), thickness=3) | |
P # show the result | |
Graphics object consisting of 5 graphics primitives | |
------------------------------------------ | |
Make some plots of sin functions: | |
f(x) = sin(x) | |
g(x) = sin(2*x) | |
h(x) = sin(4*x) | |
p1 = plot(f, (-2*pi,2*pi), color=hue(0.5)) # long time | |
p2 = plot(g, (-2*pi,2*pi), color=hue(0.9)) # long time | |
p3 = parametric_plot((f,g), (0,2*pi), color=hue(0.6)) # long time | |
p4 = parametric_plot((f,h), (0,2*pi), color=hue(1.0)) # long time | |
Now make a graphics array out of the plots: | |
graphics_array(((p1,p2), (p3,p4))) # long time | |
Graphics Array of size 2 x 2 | |
------------------------------------------ | |
One can also name the array, and then use show() or save(): | |
ga = graphics_array(((p1,p2), (p3,p4))) # long time | |
ga.show() # long time; same output as above | |
Here we give only one row: | |
p1 = plot(sin,(-4,4)) | |
p2 = plot(cos,(-4,4)) | |
ga = graphics_array([p1, p2]) | |
ga | |
Graphics Array of size 1 x 2 | |
ga.show() | |
------------------------------------------ | |
We use list_plot_loglog() and plot in a different base.: | |
list_plot_loglog(list(zip(range(1,len(yl)), yl[1:])), base=2) # long time | |
Graphics object consisting of 1 graphics primitive | |
------------------------------------------ | |
We plot several functions together by passing a list of functions as input: | |
plot([x*exp(-n*x^2)/.4 for n in [1..5]], (0, 2), aspect_ratio=.8) | |
Graphics object consisting of 5 graphics primitives | |
------------------------------------------ | |
By default, color will change from one primitive to the next. This may be controlled by modifying color option: | |
g1 = plot([x*exp(-n*x^2)/.4 for n in [1..3]], (0, 2), color='blue', aspect_ratio=.8); g1 | |
Graphics object consisting of 3 graphics primitives | |
g2 = plot([x*exp(-n*x^2)/.4 for n in [1..3]], (0, 2), color=['red','red','green'], linestyle=['-','--','-.'], aspect_ratio=.8); g2 | |
Graphics object consisting of 3 graphics primitives | |
------------------------------------------ | |
The basic options for filling a plot: | |
p1 = plot(sin(x), -pi, pi, fill='axis') | |
p2 = plot(sin(x), -pi, pi, fill='min', fillalpha=1) | |
p3 = plot(sin(x), -pi, pi, fill='max') | |
p4 = plot(sin(x), -pi, pi, fill=(1-x)/3, fillcolor='blue', fillalpha=.2) | |
graphics_array([[p1, p2], [p3, p4]]).show(frame=True, axes=False) # long time | |
------------------------------------------ | |
The basic options for filling a list of plots: | |
(f1, f2) = x*exp(-1*x^2)/.35, x*exp(-2*x^2)/.35 | |
p1 = plot([f1, f2], -pi, pi, fill={1: [0]}, fillcolor='blue', fillalpha=.25, color='blue') | |
p2 = plot([f1, f2], -pi, pi, fill={0: x/3, 1:[0]}, color=['blue']) | |
p3 = plot([f1, f2], -pi, pi, fill=[0, [0]], fillcolor=['orange','red'], fillalpha=1, color={1: 'blue'}) | |
p4 = plot([f1, f2], (x,-pi, pi), fill=[x/3, 0], fillcolor=['grey'], color=['red', 'blue']) | |
graphics_array([[p1, p2], [p3, p4]]).show(frame=True, axes=False) # long time | |
------------------------------------------ | |
Fill the area between a function and its asymptote: | |
f = (2*x^3+2*x-1)/((x-2)*(x+1)) | |
plot([f, 2*x+2], -7,7, fill={0: [1]}, fillcolor='#ccc').show(ymin=-20, ymax=20) | |
------------------------------------------ | |
Fill the area between a list of functions and the x-axis: | |
def b(n): return lambda x: bessel_J(n, x) | |
plot([b(n) for n in [1..5]], 0, 20, fill='axis') | |
Graphics object consisting of 10 graphics primitives | |
------------------------------------------ | |
This is particularly useful when setting custom ticks in multiples of pi. | |
plot(sin(x),(x,0,2*pi),ticks=pi/3,tick_formatter=pi) | |
Graphics object consisting of 1 graphics primitive | |
------------------------------------------ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Soluciones Exactas : | |
x = var('x') | |
solve(x^2 + 3*x + 2, x) | |
[x == -2, x == -1] | |
------------------------------------------ | |
Solucion en funcion de las demas variables : | |
x, b, c = var('x b c') | |
solve([x^2 + b*x + c == 0],x) | |
[x == -1/2*b - 1/2*sqrt(b^2 - 4*c), x == -1/2*b + 1/2*sqrt(b^2 - 4*c)] | |
------------------------------------------ | |
Solucion para varias variables simultaneas : | |
x, y = var('x, y') | |
solve([x+y==6, x-y==4], x, y) | |
[[x == 5, y == 1]] | |
------------------------------------------ | |
Solucion de Sistemas no Lineales : | |
var('x y p q') | |
(x, y, p, q) | |
eq1 = p+q==9 | |
eq2 = q*y+p*x==-6 | |
eq3 = q*y^2+p*x^2==24 | |
solve([eq1,eq2,eq3,p==1],p,q,x,y) | |
[[p == 1, q == 8, x == -4/3*sqrt(10) - 2/3, y == 1/6*sqrt(10) - 2/3], [p == 1, q == 8, x == 4/3*sqrt(10) - 2/3, y == -1/6*sqrt(10) - 2/3]] | |
------------------------------------------ | |
Solucion Numerica de Ecuaciones no Lineales : | |
solns = solve([eq1,eq2,eq3,p==1],p,q,x,y, solution_dict=True) | |
[[s[p].n(30), s[q].n(30), s[x].n(30), s[y].n(30)] for s in solns] | |
[[1.0000000, 8.0000000, -4.8830369, -0.13962039], | |
[1.0000000, 8.0000000, 3.5497035, -1.1937129]] | |
El argumento de n es el numero de bits de la precision deseada | |
------------------------------------------ | |
Solucion Numerica para ecuaciones complejas : | |
theta = var('theta') | |
solve(cos(theta)==sin(theta), theta) | |
[sin(theta) == cos(theta)] | |
Claramente no se obtuvo ninguna solucion, motivo por el cual pasamos al siguiente metodo de solucion : | |
phi = var('phi') | |
find_root(cos(phi)==sin(phi),0,pi/2) | |
0.785398163397448... | |
------------------------------------------ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Defincion de Funciones : | |
f(x)=x^3+1 | |
f(2) | |
9 | |
------------------------------------------ | |
In the cell below, we define an expression FV which is the future value of an investment of $100, compounded continuously. We then substitute in values for r and t which calculate the future value for t=5 years and r=5% nominal interest. | |
var('r,t') | |
(r, t) | |
FV=100*e^(r*t) | |
FV(r=.05,t=5) | |
128.402541668774 | |
------------------------------------------ | |
Notice that when we define a function, we don’t need to specify which variable has which value. In the function defined below, we have already specified an order. | |
FV2(r,t)=100*e^(r*t) | |
FV2(.05,5) | |
128.402541668774 | |
In this case it is clear that r is first and t is second. | |
But with FV=100*e^(r*t), there is no particular reason r or t should be first. | |
FV(r=.05,t=5); FV(t=5,r=.05) | |
128.402541668774 | |
128.402541668774 | |
------------------------------------------ | |
Expansion y Factorizacion : | |
z = (x+1)^3 | |
expand(z) # or z.expand() | |
x^3 + 3*x^2 + 3*x + 1 | |
y = expand(z) | |
y.factor() # or factor(y) | |
(x + 1)^3 | |
------------------------------------------ | |
Simplificacion y respresentacion simbolica del resultado : | |
z = ((x - 1)^(3/2) - (x + 1)*sqrt(x - 1))/sqrt((x - 1)*(x + 1)) | |
z.simplify_full() | |
-2*sqrt(x - 1)/sqrt(x^2 - 1) | |
z.simplify | |
<built-in method simplify of sage.symbolic.expression.Expression object at ...> | |
show(z.simplify_rational()) | |
------------------------------------------ | |
Resolucion Simultanea de una misma variable : | |
It’s also possible to solve more than one expression simultaneously. | |
solve([x^2==1,x^3==1],x) | |
[[x == 1]] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment