« Mathématiques avec Python et Ruby/Résolution de systèmes en Ruby » : différence entre les versions

Contenu supprimé Contenu ajouté
Aucun résumé des modifications
DannyS712 (discussion | contributions)
m <source> -> <syntaxhighlight> (phab:T237267)
 
Ligne 16 :
Dans le cas présent, il se trouve que ''x'' et ''y'' sont entiers naturels. Si on sait que c'est le cas, on peut les chercher par tâtonnement avec une boucle sur ''x'' et sur ''y''. On va successivement fabriquer un tableau bidimensionnel avec les entiers de 0 à 100 (deux premières lignes) puis regarder quels couples de ce tableau vérifient à la fois les deux conditions données par le système:
 
<sourcesyntaxhighlight lang="ruby">
total=[[]]
(0..100).each{|x| (0..100).each{|y| total.push([x,y])}}
solutions=total.select{|c| 3*c[0].to_f-2*c[1].to_f==-1 and c[0].to_f+c[1].to_f==8}
puts(solutions)
</syntaxhighlight>
</source>
 
=Méthode algébrique=
Ligne 27 :
Le système <math>\left\{\begin{array}{rcl}3x-2y&=&-1\\x+y&=&8 \end{array} \right.</math> peut aussi s'écrire matriciellement <math>\left(\begin{array}{rr}3 & -2 \\ 1 & 1 \end{array} \right)\left(\begin{array}{r} x \\ y \end{array} \right)=\left(\begin{array}{r} -1 \\ 8 \end{array} \right)</math> soit <math>AX=B</math> avec <math>A=\left(\begin{array}{rr}3 & -2 \\ 1 & 1 \end{array} \right)</math> et <math>B=\left(\begin{array}{r} -1 \\ 8 \end{array} \right)</math>. Alors sa solution <math>X=\left(\begin{array}{r} x \\ y \end{array} \right)</math> s'obtient par le [[w:Matrice (mathématiques)|calcul matriciel]] <math>X=A^{-1}B</math>, ce qui se fait directement avec le module ''matrix'' de ''Ruby'':
 
<sourcesyntaxhighlight lang="ruby">
require 'matrix'
require 'mathn'
Ligne 35 :
solution=A.inverse*B
puts(solution)
</syntaxhighlight>
</source>
 
En ayant choisi ''mathn'' avec, les solutions s'écrivent automatiquement sous forme de fractions si elles ne sont pas entières.