CIRM Tutoriel 1 (français) system:sage
22 February 2010
écrit par Franco Saliola, 22 février 2010
traduit en français par Sébastien Labbé le 4 mars 2010
Il y a plusieurs façons d'obtenir de l'aide en Sage.
Cliquer sur le lien Help en haut à droite de cette page. Ceci vous amène à la documentation sur l'interface notebook ainsi qu'à un lien au manuel de référence.
{{{id=145| g = Graph({0:{1:'x',2:'z',3:'a'}, 2:{5:'out'}}); g /// Graph on 5 vertices }}} {{{id=146| show(g, edge_labels=True) ///Écrivez quelque chose et appuyez sur la touche TAB. L'interface essait de compléter ce que vous avez écrit par un nom de commande. S'il y a plus d'une possibilité, celles-ci vous seront offertes.
{{{id=57| /// }}} {{{id=55| /// }}}
Pour voir la documentation et des exemples d'utilisation une commande, tapez ? à la fin de la commande et appuyez sur la touche TAB ou MAJ + ENTRÉE.? : Documentation et exemples
@options(cmap=’gray’,marker=’.’,frame=True) def matrix_plot(mat, **options):
r”“” A plot of a given matrix or 2D array.
If the matrix is dense, each matrix element is given a different color value depending on its relative size compared to the other elements in the matrix. If the matrix is sparse, colors only indicate whether an element is nonzero or zero, so the plot represents the sparsity pattern of the matrix.
The tick marks drawn on the frame axes denote the row numbers (vertical ticks) and the column numbers (horizontal ticks) of the matrix.
INPUT:
- mat - a 2D matrix or array
The following input must all be passed in as named parameters, if default not used:
- cmap - a colormap (default: ‘gray’), the name of a predefined colormap, a list of colors, or an instance of a matplotlib Colormap. Type: import matplotlib.cm; matplotlib.cm.datad.keys() for available colormap names.
EXAMPLES:
A matrix over \ZZ colored with different grey levels:
sage: matrix_plot(matrix([[1,3,5,1],[2,4,5,6],[1,3,5,7]]))Here we make a random matrix over \RR and use cmap='hsv' to color the matrix elements different RGB colors:
sage: matrix_plot(random_matrix(RDF, 50), cmap='hsv')Another random plot, but over \GF{389}:
sage: m = random_matrix(GF(389), 10) sage: matrix_plot(m, cmap='Oranges')It also works if you lift it to the polynomial ring:
sage: matrix_plot(m.change_ring(GF(389)['x']), cmap='Oranges')Here we plot a random sparse matrix:
sage: sparse = matrix(dict([((randint(0, 10), randint(0, 10)), 1) for i in xrange(100)])) sage: matrix_plot(sparse) sage: A=random_matrix(ZZ,100000,density=.00001,sparse=True) sage: matrix_plot(A,marker=',')Plotting lists of lists also works:
sage: matrix_plot([[1,3,5,1],[2,4,5,6],[1,3,5,7]])As does plotting of NumPy arrays:
sage: import numpy sage: matrix_plot(numpy.random.rand(10, 10))TESTS:
sage: P.<t> = RR[] sage: matrix_plot(random_matrix(P, 3, 3)) ... TypeError: cannot coerce nonconstant polynomial to floatsage: matrix_plot([1,2,3]) ... TypeError: mat must be a Matrix or a two dimensional arraysage: matrix_plot([[sin(x), cos(x)], [1, 0]]) ... ValueError: can not convert array entries to floating point numbers“”” import numpy as np import scipy.sparse as scipysparse from sage.plot.plot import Graphics from sage.matrix.all import is_Matrix from sage.rings.all import RDF
- if is_Matrix(mat):
sparse = mat.is_sparse() if sparse:
entries = list(mat._dict().items()) data = np.asarray([d for _,d in entries]) positions = np.asarray([[row for (row,col),_ in entries],
[col for (row,col),_ in entries]], dtype=int)mat = scipysparse.coo_matrix((data,positions), shape=(mat.nrows(), mat.ncols()))
- else:
- mat = mat.change_ring(RDF).numpy()
- elif hasattr(mat, ‘tocoo’):
- sparse = True
- else:
- sparse = False
- try:
- if sparse:
- xy_data_array = mat
- else:
- xy_data_array = np.asarray(mat, dtype = float)
- except TypeError:
- raise TypeError, “mat must be a Matrix or a two dimensional array”
- except ValueError:
- raise ValueError, “can not convert array entries to floating point numbers”
- if len(xy_data_array.shape) < 2:
- raise TypeError, “mat must be a Matrix or a two dimensional array”
xrange = (0, xy_data_array.shape[1]) yrange = (0, xy_data_array.shape[0])
g = Graphics() g._set_extra_kwds(Graphics._extract_kwds_for_show(options)) g.add_primitive(MatrixPlot(xy_data_array, xrange, yrange, options)) return g
Exercice A: Quel est le plus grand facteur premier de 600851475143?
{{{id=46| /// }}} {{{id=45| /// }}} {{{id=44| /// }}}Exercice B: Créer la permutation 51324 et assigner la à la variable p.
Exercice C: Utilisez la commande matrix pour créer la matrice suivante :
$$\left(\begin{array}{rrrr}
10 & 4 & 1 & 1 \\
4 & 6 & 5 & 1 \\
1 & 5 & 6 & 4 \\
1 & 1 & 4 & 10
\end{array}\right)$$
Voici un exemple de fonction symbolique.
{{{id=70| f(x) = x^4 - 4*x^3 - 3*x^2 + 10*x + 8 /// }}} {{{id=130| /// }}} {{{id=129| /// }}}Pour définir d'autres variables symboliques, utilisez la commande var.
{{{id=63| var('a,b,c') /// }}} {{{id=132| a*x^2 + b*x + c /// }}} {{{id=133| soln = solve(a*x^2 + b*x + c == 0, x) soln /// }}} {{{id=141| print soln /// }}} {{{id=101| show(soln) /// }}} {{{id=134| /// }}}Exercice D:
Exercice E (Advancé):
Pour définir une fonction en Sage, utiliser la commande def (et les deux points à la fin de la ligne qui commence par def !). Par exemple:
{{{id=140| def carre(x): return x^2 /// }}}Noter que le corps de la fonction (la ligne return x^2) est indentée. L'indentation définit le corps de la fonction!
Voici la forme générale d'un énoncé if .
if <expression_conditionnelle>:
<bloc_de_code>
else:
<bloc_de_code>
Noter comment le premier et le deuxième bloc de l'énoncé sont indentés.
{{{id=82| def est_impair(x): if x % 2 == 1: return True else: return False /// }}} {{{id=81| /// }}} {{{id=105| /// }}}Voici un exemple de boucle for. Elle calcule la somme des entier impairs entre 1 et 99 (100 est exclu).
{{{id=80| s = 0 for i in range(1,100): if est_impair(i): s += i print s /// 2500 }}} {{{id=79| /// }}} {{{id=78| /// }}}Exercice F. Si on liste tous les nombres naturels plus petits que 10 qui sont multiples de 3 ou 5, on obtient 3, 5, 6 et 9. La somme de ces multiples est 23.
Trouver la somme de tous les multiples de 3 ou 5 plus petits que 1000.
Exercice G. La fonction de Syracuse est définie sur les entiers positifs $n$ comme suit:
$$\text{syracuse(n)} = \begin{cases}\frac{n}{2}, & \text{si } n \text{ est pair} \\ 3n+1, & \text{si } n \text{ est impair}\end{cases}$$
Par exemple, syracuse(6) = 3 parce que 6 est pair; et syracuse(11) = 34 parce que 11 est impair.
Écrivez la fonction de Syracuse en Sage.
Exercice H. On rappelle que le factoriel d'un entier positif $n$ est le produit $$n! = n \times (n-1) \times (n-2) \times \cdots \times 1$$ Écrire une fonction qui retourne le factoriel d'un entier $n$. Écrire la fonction de sorte qu'elle utilise une boucle.
{{{id=72| /// }}} {{{id=116| /// }}} {{{id=115| /// }}} {{{id=114| /// }}} {{{id=123| /// }}}Exercice I: Si on commence avec 6 et que l'on applique la fonction de Syracuse, on obtient 3. Si on applique la fonction de Syracuse à 3, alors on obtient 10. En l'appliquant à 10, on obtient 5. En continuant ainsi, on obtient la suite $$6, 3, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1, 4, 2, 1, 4, 2, 1, \ldots$$ Noter que cette séquence a atteint la boucle $4 \mapsto 2 \mapsto 1 \mapsto 4$. La conjecture dit que c'est toujours le cas.
La conjecture $3n+1$: Pour tout $n$, la séquence atteindra toujours 1.
Écrire une fonction qui prend un entier positif et qui affiche les termes de la suite jusqu'à ce que le nombre 1 soit atteint. Par exemple avec 6, la fonction affichera
6
3
10
5
16
8
4
2
1
La boucle while sera utile ici. Voici un exemple :
x = 0
while x < 7:
x = x + 2
print x