TP-optimisation-numerique-2/julia/scr-julia/.ipynb_checkpoints/intro-julia-checkpoint.ipynb
2020-11-09 20:04:03 +01:00

1536 lines
37 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Introduction au langage julia #\n",
"## Types, id et références ##\n",
"`Julia` est un langage typé. La fonction `typeof` permet d'obtenir le type d'un objet ou d'une variable. Un seconde fonction importante pour comprendre comment sont stockés les objets est `objectid`. Cette\n",
"fonction donne l'identifiant de l'objet (en gros sa place en mémoire)."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Int64\n",
"17186855983609068021\n"
]
}
],
"source": [
"a = 3\n",
"println(typeof(a))\n",
"println(objectid(a))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Int, float, complexes, rationnels et booléens ##\n",
"### Les entiers et réels flottants\n",
"- Les types entiers signés : Int8, Int16, Int32, Int64, Int128;\n",
"- Les types entiers non signés : UInt8, UInt16, UInt32, UInt64, UInt128;\n",
"- Les réels flottants : Float16, Float32, Float64.\n",
"Par défaut, le type d'une variable est définie par son affectation, mais on peut préciser son type."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x =12\n",
"type de x : Int64\n",
"y = 12\n",
"type de y : UInt64\n",
"type de z : Float64\n"
]
}
],
"source": [
"x = 12\n",
"println(\"x =\",x)\n",
"println(\"type de x : \",typeof(x))\n",
"y = UInt64(12)\n",
"println(\"y = \",y)\n",
"println(\"type de y : \",typeof(y))\n",
"z = 1.0\n",
"println(\"type de z : \",typeof(z))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Les complexes"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a = 1 + 2im\n",
"type de a : Complex{Int64}\n"
]
}
],
"source": [
"a = 1+2im\n",
"println(\"a = \",a)\n",
"println(\"type de a : \",typeof(a))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Les rationnels"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"q = 2//3\n",
"type de qRational{Int64}\n",
"q = 13//15\n"
]
}
],
"source": [
"q = 2//3\n",
"println(\"q = \",q)\n",
"println(\"type de q\",typeof(q))\n",
"q = q + 1//5\n",
"println(\"q = \",q)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Booléens"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a = true\n",
"type de a : Bool\n"
]
}
],
"source": [
"a = true\n",
"println(\"a = \",a)\n",
"println(\"type de a : \",typeof(a))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Itérateur\n",
"1:5 est un **itérateur**"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a = 1:2:7\n",
"type de a : StepRange{Int64,Int64}\n",
"b = [1, 3, 5, 7]\n",
"type de b : Array{Int64,1}\n"
]
}
],
"source": [
"a = 1:2:7\n",
"println(\"a = \",a)\n",
"println(\"type de a : \", typeof(a))\n",
"b = collect(a) # renvoie le vecteur des valeurs\n",
"println(\"b = \",b)\n",
"println(\"type de b : \", typeof(b))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## type array"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a = [1 2 3], b = [1, 2, 3], c = [1.0 2.0 3.0; 1.0 2.0 3.0]\n",
"type de a = Array{Int64,2}, type de b = Array{Int64,1}, type de c = Array{Float64,2}\n"
]
}
],
"source": [
"a = [1 2 3]\n",
"b = [1,2,3]\n",
"c = [1.0 2 3 ; 1 2 3]\n",
"println(\"a = $a, b = $b, c = $c\")\n",
"b_type = typeof(b)\n",
"a_type = typeof(a)\n",
"c_type = typeof(c)\n",
"println(\"type de a = $a_type, type de b = $b_type, type de c = $c_type\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- a est une matrice d'entier à 1 ligne, 3 colonnes\n",
"- b est un vecteur d'entier\n",
"- c est une matrice de flottants 2 lignes, 3 colonnes\n",
"Que se passe-t-il si on calcul : `a*b, b*a, c*b, c*a`"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1-element Array{Int64,1}:\n",
" 14"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a*b"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3×3 Array{Int64,2}:\n",
" 1 2 3\n",
" 2 4 6\n",
" 3 6 9"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b*a"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [
{
"ename": "DimensionMismatch",
"evalue": "DimensionMismatch(\"matrix A has dimensions (2,3), matrix B has dimensions (1,3)\")",
"output_type": "error",
"traceback": [
"DimensionMismatch(\"matrix A has dimensions (2,3), matrix B has dimensions (1,3)\")",
"",
"Stacktrace:",
" [1] _generic_matmatmul!(::Array{Float64,2}, ::Char, ::Char, ::Array{Float64,2}, ::Array{Int64,2}, ::LinearAlgebra.MulAddMul{true,true,Bool,Bool}) at /Users/julia/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.4/LinearAlgebra/src/matmul.jl:736",
" [2] generic_matmatmul!(::Array{Float64,2}, ::Char, ::Char, ::Array{Float64,2}, ::Array{Int64,2}, ::LinearAlgebra.MulAddMul{true,true,Bool,Bool}) at /Users/julia/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.4/LinearAlgebra/src/matmul.jl:724",
" [3] mul! at /Users/julia/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.4/LinearAlgebra/src/matmul.jl:235 [inlined]",
" [4] mul! at /Users/julia/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.4/LinearAlgebra/src/matmul.jl:208 [inlined]",
" [5] *(::Array{Float64,2}, ::Array{Int64,2}) at /Users/julia/buildbot/worker/package_macos64/build/usr/share/julia/stdlib/v1.4/LinearAlgebra/src/matmul.jl:153",
" [6] top-level scope at In[10]:1"
]
}
],
"source": [
"c*a"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2-element Array{Float64,1}:\n",
" 14.0\n",
" 14.0"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"c*b"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"b est donc un vecteur colonne"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Opérations terme à terme\n",
"On a bien sur les opétations classique : + * et /, l'étoile \n",
"\\* est la multiplication matricielle pais on a aussi les opérations terme à terme"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2×3 Array{Float64,2}:\n",
" 2.0 4.0 6.0\n",
" 2.0 4.0 6.0"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"d = 2*ones(2,3)\n",
"c .* d"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Attention au .** Étant donné que le point . permet à la fois de définir un float et d'effectuer\n",
"les opérations élément par élément, il faut mettre des espaces entre les points afin de pouvoir distinguer\n",
"la signification de chaque point."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2-element Array{Float64,1}:\n",
" 6.0\n",
" 7.0"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"5. .+ [1,2]"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"ename": "LoadError",
"evalue": "syntax: invalid syntax \"5.+\"; add space(s) to clarify",
"output_type": "error",
"traceback": [
"syntax: invalid syntax \"5.+\"; add space(s) to clarify",
""
]
}
],
"source": [
"5.+[1,2]"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"E = 1:4\n",
"type de E : UnitRange{Int64}\n"
]
}
],
"source": [
"E = 1:4\n",
"println(\"E = \",E)\n",
"println(\"type de E : \",typeof(E))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"On peut extraire des sous matrice facilement, mais attention "
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2×2 Array{Int64,2}:\n",
" 1 2\n",
" 9 10"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"E = [1 2 3 4 ; 5 6 7 8 ; 9 10 11 12]\n",
"E[[1,3],1:2]"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"ename": "ArgumentError",
"evalue": "ArgumentError: invalid index: UnitRange{Int64}[1:2] of type Array{UnitRange{Int64},1}",
"output_type": "error",
"traceback": [
"ArgumentError: invalid index: UnitRange{Int64}[1:2] of type Array{UnitRange{Int64},1}",
"",
"Stacktrace:",
" [1] to_index(::Array{UnitRange{Int64},1}) at ./indices.jl:294",
" [2] to_index(::Array{Int64,2}, ::Array{UnitRange{Int64},1}) at ./indices.jl:274",
" [3] to_indices at ./indices.jl:325 [inlined] (repeats 2 times)",
" [4] to_indices at ./indices.jl:321 [inlined]",
" [5] getindex(::Array{Int64,2}, ::Array{Int64,1}, ::Array{UnitRange{Int64},1}) at ./abstractarray.jl:980",
" [6] top-level scope at In[17]:1"
]
}
],
"source": [
"E[[1,3],[1:2]]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Les tuples\n",
"Ce sont des sortes de tableaux à 1 dimension dont les objets peuvent avoir des types différents. Ce sont des objet non modifiables"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(12, 13, \"quatorze\")"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"t = 12, 13, \"quatorze\""
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"12"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"t[1]"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"quatorze\""
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"t[3]"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Tuple{Int64,Int64,String}"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"typeof(t)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"ename": "MethodError",
"evalue": "MethodError: no method matching setindex!(::Tuple{Int64,Int64,String}, ::Int64, ::Int64)",
"output_type": "error",
"traceback": [
"MethodError: no method matching setindex!(::Tuple{Int64,Int64,String}, ::Int64, ::Int64)",
"",
"Stacktrace:",
" [1] top-level scope at In[22]:1"
]
}
],
"source": [
"t[2]=1 # erreur car non modifiable"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Autres types de base\n",
"* les chaînes de caractères;\n",
"* les dictionnaires;\n",
"* les ensembles.\n",
"\n",
"On peut aussi créer des types : structures, ..."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Fonctions\n",
"**Les paramètres de type scalaire ou tuple sont en entrée**"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Avant fct2\n",
"objectid(a) = 9949443806018717880, objectid(b) = 11967854120867199718\n",
"a, b = 0, 1\n",
"Dans fct2\n",
"objectid(a) = 9949443806018717880, objectid(b) = 11967854120867199718\n",
"objectid(a) = 9949443806018717880, objectid(b) = 9949443806018717880\n",
"Après fct2\n",
"objectid(a) = 9949443806018717880, objectid(b) = 11967854120867199718\n",
"a, b, c = 0,1,0\n"
]
}
],
"source": [
"function fct2(a,b)\n",
" a_id = objectid(a)\n",
" b_id = objectid(b)\n",
" println(\"objectid(a) = $a_id, objectid(b) = $b_id\")\n",
" b = a\n",
" a_id = objectid(a)\n",
" b_id = objectid(b)\n",
" println(\"objectid(a) = $a_id, objectid(b) = $b_id\")\n",
" return b\n",
"end\n",
"a = 0\n",
"b = 1\n",
"a_id = objectid(a)\n",
"b_id = objectid(b)\n",
"println(\"Avant fct2\")\n",
"println(\"objectid(a) = $a_id, objectid(b) = $b_id\")\n",
"println(\"a, b = $a, $b\")\n",
"println(\"Dans fct2\")\n",
"c = fct2(a,b)\n",
"println(\"Après fct2\")\n",
"a_id = objectid(a)\n",
"b_id = objectid(b)\n",
"println(\"objectid(a) = $a_id, objectid(b) = $b_id\")\n",
"println(\"a, b, c = $a,$b,$c\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Type Array\n",
"\n",
"**Les paramètres sont passés par référence**"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Avant fct3\n",
"objectid(a) = 15031927814252516001, objectid(b) = 13102773869306322552\n",
"a, b = [0, 0], [1, 1]\n",
"Dans fct3\n",
"objectid(a) = 15031927814252516001, objectid(b) = 13102773869306322552\n",
"objectid(a) = 15031927814252516001, objectid(b) = 13102773869306322552\n",
"a, b = [0, 0], [0, 0]\n",
"Après fct3\n",
"objectid(a) = 15031927814252516001, objectid(b) = 13102773869306322552, objectid(c) = 13102773869306322552\n",
"a, b, c = [0, 0], [0, 0], [0, 0]\n",
"b = [10, 0], c = [10, 0]\n"
]
}
],
"source": [
"function fct3(a,b)\n",
" a_id = objectid(a)\n",
" b_id = objectid(b)\n",
" println(\"objectid(a) = $a_id, objectid(b) = $b_id\")\n",
" b[1] = a[1]\n",
" b[2] = a[2]\n",
" a_id = objectid(a)\n",
" b_id = objectid(b)\n",
" println(\"objectid(a) = $a_id, objectid(b) = $b_id\")\n",
" println(\"a, b = $a, $b\")\n",
" return b \n",
"end\n",
"a = [0,0]\n",
"b = [1,1]\n",
"a_id = objectid(a)\n",
"b_id = objectid(b)\n",
"println(\"Avant fct3\")\n",
"println(\"objectid(a) = $a_id, objectid(b) = $b_id\")\n",
"println(\"a, b = $a, $b\")\n",
"println(\"Dans fct3\")\n",
"c = fct3(a,b)\n",
"println(\"Après fct3\")\n",
"a_id = objectid(a)\n",
"b_id = objectid(b)\n",
"c_id = objectid(c)\n",
"println(\"objectid(a) = $a_id, objectid(b) = $b_id, objectid(c) = $c_id\")\n",
"println(\"a, b, c = $a, $b, $c\")\n",
"c[1]=10\n",
"println(\"b = $b, c = $c\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**`b`et `c`sont les mêmes objects!**\n",
"\n",
"**`a` et `b` sont les mêmes objets**"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Avant fct3_1\n",
"objectid(a) = 6846767276606612758, objectid(b) = 16616932192875253576\n",
"a, b = [0, 0], [1, 1]\n",
"Dans fct3_1\n",
"objectid(a) = 6846767276606612758, objectid(b) = 16616932192875253576\n",
"objectid(a) = 6846767276606612758, objectid(b) = 16616932192875253576\n",
"a, b = [0, 0], [0, 0]\n",
"Après fct3_1\n",
"objectid(a) = 6846767276606612758, objectid(b) = 16616932192875253576, objectid(c) = 208917430185405003\n",
"a, b, c = [0, 0], [0, 0], [0, 0]\n",
"b = [0, 0], c = [10, 0]\n"
]
}
],
"source": [
"function fct3_1(a,b)\n",
" a_id = objectid(a)\n",
" b_id = objectid(b)\n",
" println(\"objectid(a) = $a_id, objectid(b) = $b_id\")\n",
" b[1] = a[1]\n",
" b[2] = a[2]\n",
" a_id = objectid(a)\n",
" b_id = objectid(b)\n",
" println(\"objectid(a) = $a_id, objectid(b) = $b_id\")\n",
" println(\"a, b = $a, $b\")\n",
" return b[:] # on renvoie un nouvel objet \n",
"end\n",
"a = [0,0]\n",
"b = [1,1]\n",
"a_id = objectid(a)\n",
"b_id = objectid(b)\n",
"println(\"Avant fct3_1\")\n",
"println(\"objectid(a) = $a_id, objectid(b) = $b_id\")\n",
"println(\"a, b = $a, $b\")\n",
"println(\"Dans fct3_1\")\n",
"c = fct3_1(a,b)\n",
"println(\"Après fct3_1\")\n",
"a_id = objectid(a)\n",
"b_id = objectid(b)\n",
"c_id = objectid(c)\n",
"println(\"objectid(a) = $a_id, objectid(b) = $b_id, objectid(c) = $c_id\")\n",
"println(\"a, b, c = $a, $b, $c\")\n",
"c[1]=10\n",
"println(\"b = $b, c = $c\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**`b`et `c`sont différents**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- le contenu du vecteur b a été modifié;\n",
"- le pointeur sur le vecteur b est le même."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**`fct`et `fct!` donnent les mêmes résultats**. Par convention on aura un ! à la fin du nom de la fonction si au moins un des paramètres en entrée est modifié (en général le premier)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Arguments\n",
"- arguments optionnels;\n",
"- vectorisation : `sin.([0,\\pi/2,\\pi])`;\n",
"- `Maps`et `Filters`(programmation fonctionnelle);\n",
"- récursivité."
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Number\n",
"\tComplex\n",
"\tReal\n",
"\t\tAbstractFloat\n",
"\t\t\tBigFloat\n",
"\t\t\tFloat16\n",
"\t\t\tFloat32\n",
"\t\t\tFloat64\n",
"\t\tAbstractIrrational\n",
"\t\t\tIrrational\n",
"\t\tInteger\n",
"\t\t\tBool\n",
"\t\t\tSigned\n",
"\t\t\t\tBigInt\n",
"\t\t\t\tInt128\n",
"\t\t\t\tInt16\n",
"\t\t\t\tInt32\n",
"\t\t\t\tInt64\n",
"\t\t\t\tInt8\n",
"\t\t\tUnsigned\n",
"\t\t\t\tUInt128\n",
"\t\t\t\tUInt16\n",
"\t\t\t\tUInt32\n",
"\t\t\t\tUInt64\n",
"\t\t\t\tUInt8\n",
"\t\tRational\n"
]
}
],
"source": [
" function showtypetree(T, level=0)\n",
" println(\"\\t\" ^ level, T)\n",
" for t in subtypes(T)\n",
" if t != Any\n",
" showtypetree(t, level+1)\n",
" end\n",
" end\n",
" end\n",
" \n",
" showtypetree(Number)"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"type de A = Array{Real,1}, type de B = Array{Real,1}\n",
"Real[#undef, #undef, #undef]\n",
"type de A = Array{Real,2}, type de B = Array{Real,2}\n"
]
},
{
"data": {
"text/plain": [
"true"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# vecteur\n",
"A = Array{Real}(undef,3)\n",
"B = Vector{Real}(undef,4)\n",
"A_type = typeof(A)\n",
"B_type = typeof(B)\n",
"println(\"type de A = $A_type, type de B = $B_type\")\n",
"\n",
"println(A)\n",
"A_type == B_type # renvoie true\n",
"#\n",
"# Matrices\n",
"A = Array{Real}(undef,2,4)\n",
"B = Matrix{Real}(undef,3,4)\n",
"A_type = typeof(A)\n",
"B_type = typeof(B)\n",
"println(\"type de A = $A_type, type de B = $B_type\")\n",
"A_type == B_type # renvoie true "
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"true"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Int<:Real"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"false"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Int<:AbstractFloat"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Types dans les fonctions\n",
"### Paramètres en entrée\n",
"\n",
"Si les paramètres ne sont pas du bon type alors le programme plante"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"ename": "MethodError",
"evalue": "MethodError: no method matching fct5(::Float64, ::Int64)\nClosest candidates are:\n fct5(!Matched::Int64, ::Int64) at In[30]:2",
"output_type": "error",
"traceback": [
"MethodError: no method matching fct5(::Float64, ::Int64)\nClosest candidates are:\n fct5(!Matched::Int64, ::Int64) at In[30]:2",
"",
"Stacktrace:",
" [1] top-level scope at In[30]:4"
]
}
],
"source": [
"function fct5(a::Int, b::Int)\n",
" return a+b\n",
"end\n",
"f1 = fct5(2.,2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Paramètre en sortie"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Main Program, test of fct6!\n",
"--------------------------\n",
"a, x = 1, [0, 0]\n",
"f_a, f_x = a, [2, 2]\n",
"Main Program, test of fct7!\n",
"--------------------------\n"
]
},
{
"ename": "MethodError",
"evalue": "MethodError: Cannot `convert` an object of type String to an object of type Int64\nClosest candidates are:\n convert(::Type{T}, !Matched::T) where T<:Number at number.jl:6\n convert(::Type{T}, !Matched::Number) where T<:Number at number.jl:7\n convert(::Type{T}, !Matched::Ptr) where T<:Integer at pointer.jl:23\n ...",
"output_type": "error",
"traceback": [
"MethodError: Cannot `convert` an object of type String to an object of type Int64\nClosest candidates are:\n convert(::Type{T}, !Matched::T) where T<:Number at number.jl:6\n convert(::Type{T}, !Matched::Number) where T<:Number at number.jl:7\n convert(::Type{T}, !Matched::Ptr) where T<:Integer at pointer.jl:23\n ...",
"",
"Stacktrace:",
" [1] convert(::Type{Tuple{Int64,Array{T,1} where T}}, ::Tuple{String,Array{Int64,1}}) at ./essentials.jl:310",
" [2] fct7!(::Int64, ::Array{Int64,1}) at ./In[31]:11",
" [3] top-level scope at In[31]:26"
]
}
],
"source": [
"function fct6!(a::Real ,x::Vector)\n",
"#function fct(a::Real ,x::Vector, y::Vector)\n",
" a = \"a\" # a is a new variable\n",
" x = [2,2] # x is new variable\n",
" return a, x\n",
"end\n",
"\n",
"function fct7!(a::Real ,x::Vector)::Tuple{Int,Vector}\n",
" a = \"a\" # a is a new variable\n",
" x = [2,2] # x is new variable\n",
" return a, x\n",
"end\n",
"\n",
"println(\"Main Program, test of fct6!\")\n",
"println(\"--------------------------\")\n",
"a = 1\n",
"x = [0, 0]\n",
"f_a, f_x = fct6!(a, x)\n",
"println(\"a, x = $a, $x\")\n",
"println(\"f_a, f_x = $f_a, $f_x\")\n",
"\n",
"println(\"Main Program, test of fct7!\")\n",
"println(\"--------------------------\")\n",
"a = 1\n",
"x = [0, 0]\n",
"f_a, f_x = fct7!(a, x)\n",
"println(\"a, x, = $a, $x\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Dispatch multiple"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"f1 = 4, f2 = 0.0\n"
]
}
],
"source": [
"function fct5(a::Real, b::Int)\n",
" return a-b\n",
"end\n",
"f1 = fct5(2,2)\n",
"f2 = fct5(2.0,2)\n",
"println(\"f1 = $f1, f2 = $f2\")"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"# 2 methods for generic function <b>fct5</b>:<ul><li> fct5(a::<b>Int64</b>, b::<b>Int64</b>) in Main at In[30]:2</li> <li> fct5(a::<b>Real</b>, b::<b>Int64</b>) in Main at In[32]:2</li> </ul>"
],
"text/plain": [
"# 2 methods for generic function \"fct5\":\n",
"[1] fct5(a::Int64, b::Int64) in Main at In[30]:2\n",
"[2] fct5(a::Real, b::Int64) in Main at In[32]:2"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"methods(fct5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Portée des variables\n",
"De nombreux langages de programmation font la différence entre les variables globales (communes à tout le programme) et les variables locales, qui correspondent aux variables introduites dans le code d'une fonction\n",
"Ici, la situation est un peu plus complexe, car la philosophie générale est d'aller vers une localisation plus forte des variables de manière à éviter des conflits de noms pouvant induire des comportements non voulus.\n",
"Ce renforcement du cloisonnement se fait de deux manières :\n",
"* Une variable déclarée dans le programme principal (ou en ligne de commande REPL) n'est pas immédiatement accessible dans les blocs for. . . end, while. . . end,try. . . end du programme principal, non plus que dans les fonctions appelées par le programme. Leur appel doit être précédé du mot global.\n",
"* Une variable déclarée dans une fonction est visible dans toute fonction interne à cette fonction, ainsi que dans les blocs for. . . end, while. . . end,try. . . end de cette fonction.\n",
"* Si dans un bloc de code la déclaration d'une variable est précédée du mot clef local, c'est une nouvelle variable locale qui est créée. Elle sera détruite à la fin du bloc; si une variable précédente existait, c'est à nouveau elle qui a la main."
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"niveau_un (generic function with 1 method)"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"function niveau_un() \n",
" function niveau_deux()\n",
" x=3;\n",
" println(\"x=\",x) \n",
" end\n",
" function niveau_deux_deux()\n",
" local x=5; \n",
" println(\"x=\",x)\n",
" end\n",
" x=1; \n",
" println(\"x=\",x) \n",
" for i=1:1\n",
" x=4;\n",
" end\n",
" println(\"x=\",x)\n",
" niveau_deux();\n",
" println(\"x=\",x)\n",
" niveau_deux_deux();\n",
" println(\"x=\",x)\n",
"end"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x=1\n",
"x=4\n",
"x=3\n",
"x=3\n",
"x=5\n",
"x=3\n"
]
}
],
"source": [
"niveau_un()"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x = 1\n",
"après le for x = 4\n",
"x = 3\n",
"x = 4\n",
"x = 5\n",
"x = 4\n"
]
}
],
"source": [
"function niveau_deux()\n",
" x=3;\n",
" println(\"x = \",x) \n",
" end\n",
"function niveau_deux_deux()\n",
" local x=5; \n",
" println(\"x = \",x)\n",
"end\n",
"x = 1;\n",
"println(\"x = \",x)\n",
"for i = 1:1\n",
" x = 4;\n",
"end\n",
"println(\"après le for x = \",x)\n",
"niveau_deux();\n",
"println(\"x = \",x)\n",
"niveau_deux_deux()\n",
"println(\"x = \",x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**mais sous julia REPL on obtient pour `x`après le for 1 !**"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Performance"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" 0.012944 seconds (3.65 k allocations: 80.641 KiB)\n",
"Permormance1 = 503.0964853516044\n",
" 0.000240 seconds (3.49 k allocations: 70.156 KiB)\n",
"Permormance2 = 503.0964853516044\n"
]
}
],
"source": [
"x = rand(1000);\n",
"\n",
"function sum_global()\n",
" s = 0.0\n",
" for i in x\n",
" s += i\n",
" end\n",
" return s\n",
"end;\n",
"\n",
"p1 = @time sum_global()\n",
"println(\"Permormance1 = $p1\")\n",
"\n",
"p2 = @time sum_global()\n",
"println(\"Permormance2 = $p2\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"On the first call (@time sum_global()) the function gets compiled. (If you've not yet used @time in this session, it will also compile functions needed for timing.) You should not take the results of this run seriously. For the second run, note that in addition to reporting the time, it also indicated that a significant amount of memory was allocated. We are here just computing a sum over all elements in a vector of 64-bit floats so there should be no need to allocate memory (at least not on the heap which is what @time reports)."
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" 0.009822 seconds (5.25 k allocations: 241.867 KiB)\n",
"Permormance1 = 503.8521806777714\n",
" 0.000004 seconds (1 allocation: 16 bytes)\n",
"Permormance2 = 503.8521806777714\n"
]
}
],
"source": [
"x = rand(1000);\n",
"\n",
"function sum_arg(x)\n",
" s = 0.0\n",
" for i in x\n",
" s += i\n",
" end\n",
" return s\n",
"end;\n",
"\n",
"p1 = @time sum_arg(x)\n",
"println(\"Permormance1 = $p1\")\n",
"\n",
"p2 = @time sum_arg(x)\n",
"println(\"Permormance2 = $p2\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Conclusion : attention aux variables globales!"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"sumofsins2 (generic function with 1 method)"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"function sumofsins1(n::Integer) \n",
" r = 0 \n",
" for i in 1:n \n",
" r += sin(3.4) \n",
" end \n",
" return r \n",
"end \n",
"\n",
"function sumofsins2(n::Integer) \n",
" r = 0.0 \n",
" for i in 1:n \n",
" r += sin(3.4) \n",
" end \n",
" return r \n",
"end "
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" 0.085448 seconds (125.55 k allocations: 6.676 MiB)\n",
" 0.079326 seconds (118.57 k allocations: 6.369 MiB)\n"
]
}
],
"source": [
"sumofsins1(100_000) \n",
"sumofsins2(100_000) \n",
"\n",
"@time [sumofsins1(100_000) for i in 1:100]; \n",
"@time [sumofsins2(100_000) for i in 1:100];"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" 0.116044 seconds (125.54 k allocations: 6.647 MiB, 15.46% gc time)\n",
" 0.098289 seconds (118.57 k allocations: 6.369 MiB)\n"
]
}
],
"source": [
"@time [sumofsins1(100_000) for i in 1:100]; \n",
"@time [sumofsins2(100_000) for i in 1:100];"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Autres points\n",
"### Modules\n",
"### Interface programme en C, en fortran, ...\n",
"### Calcul parallèle\n",
"### ..."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Remarques\n",
"### Caractères UTF-8"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"ename": "UndefVarError",
"evalue": "UndefVarError: β not defined",
"output_type": "error",
"traceback": [
"UndefVarError: β not defined",
"",
"Stacktrace:",
" [1] top-level scope at In[42]:1"
]
}
],
"source": [
"β\n",
"α = 10. # on tape \\alp puis TAB, on obtient \\alpha et on retape TAB et on a le caractère grec"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'é': Unicode U+00E9 (category Ll: Letter, lowercase)"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"ch = \"élément\"\n",
"ch[1]"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"ename": "StringIndexError",
"evalue": "StringIndexError(\"élément\", 2)",
"output_type": "error",
"traceback": [
"StringIndexError(\"élément\", 2)",
"",
"Stacktrace:",
" [1] string_index_err(::String, ::Int64) at ./strings/string.jl:12",
" [2] getindex_continued(::String, ::Int64, ::UInt32) at ./strings/string.jl:220",
" [3] getindex(::String, ::Int64) at ./strings/string.jl:213",
" [4] top-level scope at In[44]:1"
]
}
],
"source": [
"ch[2]"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'l': ASCII/Unicode U+006C (category Ll: Letter, lowercase)"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"ch[3]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Inconvénients\n",
"* la portée des variables;\n",
"* la possibilité dans une fonction de créer une variable (locale) de même nom qu'un paramètre formel;\n",
"* On compile à la volé lors de chaque lancement d'une session. Possibilité de générer du code compiler?"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Julia 1.4.1",
"language": "julia",
"name": "julia-1.4"
},
"language_info": {
"file_extension": ".jl",
"mimetype": "application/julia",
"name": "julia",
"version": "1.4.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}