Documentation des modules
module1 - Gestion des opérations mathématiques de base.
Pour voir les tests unitaires s’afficher dans l’éditeur
>>> \begin{python}
>>> # Code Python : Ecrivez ci-dessous votre code Python
>>> from src.scripts.tests.test_module1 import print_tests_module1
>>> print_tests_module1()
>>> \end{python}
- module1.addition(a: float, b: float) float[source]
Additionne deux nombres.
- Parameters:
a (float) – Le premier opérande.ssssssss
b (float) – Le second opérande.
- Returns:
La somme de a et b.
- Return type:
float
Examples
>>> addition(2, 3) 5
>>> addition(1.5, 2.5) 4.0
- class module1.Calculatrice[source]
Bases:
objectClasse de calcul simple.
module2 - Fonctions sur les chaînes.
Classes_Extensions
- Classes_Extensions.pxsl_pow(x, n=1, opt=0, displaystyle=True)[source]
Fr : Fonction permettant d’écrire le nombre x entouré de parenthèses lorsqu’il est négatif ou irrationnel avec deux termes (par ex : 1+sqrt(2) ou 3sqrt(2)) Ne fonctionne pas pour des valeurs numériques non simplifiées (par ex : 1+3 ou 3*3/2) En : Function that writes the number x surrounded by parentheses when it is negative or irrational with two terms (e.g.: 1+sqrt(2) or 3sqrt(2)) Does not work for unsimplified numerical values (e.g.: 1+3 or 3*3/2)
Version 5
13/02/25
Vérification
Auteur : Delphine Vérificateurs : ??
Paramètres
- xnombre ou expression
La base à élever à la puissance n
- nint, optional
L’exposant (défaut: 1)
- optint, optional
Option de formatage (défaut: 0) 0: formatage standard 1: simplifie l’affichage pour x=1, x=0 ou n=1 2: simplifie davantage et renvoie une chaîne vide pour x=0
- displaystylebool, optional
Si True, utilise displaystyle pour les fractions (défaut: False)
Retour
- str
retourne l’expression en latex
Fonction utilisée par
pxsl_sum_matrix, pxsl_prod_scalar_matrix, pxsl_prod_matrix, pxsl_pow_matrix
- class Classes_Extensions.pxs_Interval(start, end, left_open=False, right_open=False)[source]
Classe personnalisée héritant de Interval de SymPy Permet un affichage formaté des intervalles avec : - Séparateurs de milliers pour les grands nombres - Notation française pour l’infini et les intervalles
- print(res_num=False, dec=4)[source]
Méthode pour générer une représentation LaTeX formatée de l’intervalle
- Returns:
Chaîne LaTeX formatée selon les conventions françaises
- Return type:
str
- default_assumptions = {}
- class Classes_Extensions.ReverseString(string)[source]
Classe utilitaire pour inverser l’ordre de tri des chaînes de caractères. Utilisée pour trier les variables dans l’ordre inverse alphabétique.
- class Classes_Extensions.pxs_Poly(rep, *gens, **args)[source]
Extension de la classe Poly de SymPy avec une méthode d’affichage personnalisée. Permet d’afficher les polynômes avec un formatage LaTeX personnalisé et une factorisation optionnelle.
- classmethod pxs_generate(x=x, lim_coeff=9, nb_root=None)[source]
Génère un polynôme du second degré avec des coefficients aléatoires non nuls, en contrôlant optionnellement le nombre de racines réelles.
- Parameters:
x – Variable symbolique du polynôme (par défaut Symbol(“x”))
lim_coeff – Valeur maximale absolue des coefficients (par défaut 9)
nb_root – Nombre de racines réelles souhaité (0, 1, 2 ou None pour aléatoire)
- Returns:
Un objet pxs_Poly représentant le polynôme ax² + bx + c généré
- pxsl_print(variable=None, ascending=False, displaystyle=True, factor=False)[source]
Affiche le polynôme avec un formatage LaTeX personnalisé.
Paramètres: - variable: Variable principale pour l’organisation/factorisation (None = auto-détection) - ascending: Si True, trie par puissances croissantes, sinon décroissantes - displaystyle: Si True, utilise le style d’affichage LaTeX étendu - factor: Si True, factorise le polynôme par rapport à la variable spécifiée
Retourne: - String: Expression LaTeX formatée
- pxsl_discriminant(mult='\\times', formula=True)[source]
Calcule et affiche le discriminant d’une équation du second degré au format LaTeX.
- Parameters:
mult – Symbole de multiplication à utiliser (par défaut imes en LaTeX)
- Returns:
Un objet myst contenant l’affichage LaTeX du calcul du discriminant
- pxsl_solution(mult='\\times', formula=True, inline=True, variable=True)[source]
Affiche la ou les solutions d’une équation du second degré au format LaTeX.
- Parameters:
mult – Symbole de multiplication à utiliser (par défaut imes en LaTeX)
- Returns:
x1_complet, x2_complet : calculs détaillés étape par étape
x1_final, x2_final : formes finales simplifiées
Retourne (None, None, None, None) si pas de solution réelle
- Return type:
Un tuple de 4 éléments (x1_complet, x2_complet, x1_final, x2_final) où
- pxs_factor(variable=None, display='\\displaystyle')[source]
Factorise un polynôme en utilisant sympy.Poly. Prend un objet Poly en argument.
- rep
- gens
- default_assumptions = {'commutative': True}
- is_commutative: bool | None = True
- class Classes_Extensions.pxs_SeqFormula(formula, limits=None)[source]
Sous-classe de SeqFormula offrant une méthode de sommation des coefficients. La méthode pxsl_summation produit une expression (myst) représentant la somme des coefficients de la suite entre deux indices, soit en valeur numérique, soit en notation symbolique.
- pxsl_summation(min=0, max=9, symbolic=None)[source]
Génère l’expression de la somme des coefficients u_min + u_{min+1} + … + u_{max-1}.
Paramètres: - min (int) : indice de départ de la sommation (inclu). - max (int) : indice de fin de la sommation (exclu). - symbolic (str ou None) : nom du symbole à utiliser pour la notation symbolique;
si None, on utilise self.coeff(i) pour extraire les valeurs numériques.
Retourne: - expr : un objet myst contenant la somme formatée.
- default_assumptions = {'commutative': True}
- is_commutative: bool | None = True
- class Classes_Extensions.pxs_Plotable(expr)[source]
Cette classe permet de représenter graphiquement des fonctions ou suites mathématiques d’une ou plusieurs variables définies par des expressions SymPy (fraphes 2D, 3D, fonctions partielles, suites).
Voir la documentation de chaque fonction, et la fonction tests_visuels_pxs_Plotable() du fichier de test correspondant pour un aperçu graphique général.
- __init__(expr)[source]
Initialise un objet pxs_Plotable pour le tracé de fonctions SymPy.
Cette classe permet de représenter graphiquement des fonctions ou suites mathématiques d’une ou plusieurs variables définies par des expressions SymPy (fraphes 2D, 3D, fonctions partielles, suites).
Paramètres
- exprstr, sympy.Expr
L’expression mathématique à tracer. Peut être une chaîne de caractères (qui sera convertie automatiquement) ou une expression SymPy.
Exemples
>>> from sympy.abc import x, y >>> pex1 = pxs_Plotable("cos(x)") >>> pex2 = pxs_Plotable(x**2 + y**2) >>> pex3 = pxs_Plotable(5) # fonction constante
- plot(interv=Interval(-5, 5), pas=None, ymin=None, ymax=None, title=True, fast=False, **kwargs)[source]
Trace la courbe représentative d’une fonction d’une variable.
Cette méthode trace le graphe d’une fonction à une variable ou d’une constante. Elle gère automatiquement les bornes infinies et les intervalles ouverts.
Paramètres
- intervpxs_Interval, optionnel
L’intervalle de tracé. Par défaut [-5, 5].
- pasfloat, optionnel
Le pas d’échantillonnage. Par défaut (b-a)/1000.
- titlebool, optionnel
Afficher ou non le titre avec l’expression LaTeX. Par défaut True.
- fastbool, optionnel
Mode de tracé rapide utilisant plt directement. Par défaut False.
- **kwargs
Arguments supplémentaires passés à matplotlib.pyplot.plot.
Lève
- ValueError
Si l’expression contient plus d’une variable libre.
Exemples
>>> from sympy.abc import x >>> pex = pxs_Plotable("cos(x)") >>> pex.plot() # Trace cos(x) sur [-5, 5] >>> pex.plot(interv=pxs_Interval(0, 2*pi), color="red") >>> >>> # Intervalle ouvert >>> pex_log = pxs_Plotable("log(x)") >>> pex_log.plot(interv=pxs_Interval.open(0, 5))
- plot_partial(plot_var=None, fixes=None, **kwargs)[source]
Trace la courbe d’une fonction partielle en fixant certaines variables.
Cette méthode permet de tracer une fonction de plusieurs variables en fixant toutes les variables sauf une. La figure obtenue est une courbe dans le plan.
Paramètres
- plot_varsympy.Symbol, optionnel
La variable selon laquelle tracer. Par défaut, la première variable de l’expression.
- fixesdict, optionnel
Dictionnaire {variable: valeur} fixant les autres variables. Par défaut, toutes les autres variables sont fixées à 0.
- **kwargs
Arguments supplémentaires passés à la méthode plot().
Lève
- ValueError
Si l’expression est constante, si plot_var n’appartient pas aux variables de l’expression, si certaines variables ne sont pas fixées, ou si une valeur fixée correspond à une singularité.
Exemples
>>> from sympy.abc import x, y, t >>> pex = pxs_Plotable(2*x**2 + 3*y/t) >>> # Trace selon x avec y=1, t=1 >>> pex.plot_partial(x, {y: 1, t: 1}) >>> # Trace selon t avec x=1, y=1, évite t=0 (singularité) >>> pex.plot_partial(t, {x: 1, y: 1}, interv=pxs_Interval.open(0, 5))
- plot_surface(interv1=Interval(-5, 5), interv2=Interval(-5, 5), nb_points=30, cmap='viridis', title=True, **kwargs)[source]
Trace la surface représentative d’une fonction de deux variables.
Cette méthode génère un tracé 3D de la surface définie par une fonction à exactement deux variables.
Paramètres
- interv1pxs_Interval, optionnel
Intervalle pour la première variable. Par défaut [-5, 5].
- interv2pxs_Interval, optionnel
Intervalle pour la deuxième variable. Par défaut [-5, 5].
- nb_pointsint, optionnel
Nombre de points par axe pour la grille. Par défaut 30.
- cmapstr, optionnel
Colormap matplotlib pour la surface. Par défaut “viridis”.
- titlebool, optionnel
Afficher ou non le titre avec l’expression LaTeX. Par défaut True.
- **kwargs
Arguments supplémentaires passés à matplotlib.Axes3D.plot_surface.
Lève
- ValueError
Si l’expression ne contient pas exactement deux variables libres.
Exemples
>>> from sympy.abc import x, y >>> surf1 = pxs_Plotable(x**2 + y**2) # Paraboloïde >>> fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) >>> surf1.plot_surface(cmap="plasma") >>> >>> surf2 = pxs_Plotable("sin(x)*cos(y)") # Surface trigonométrique >>> surf2.plot_surface(nb_points=50, cmap="coolwarm")
- plot_surface_partial(plot_vars=None, fixes=None, **kwargs)[source]
Trace la surface d’une fonction partielle en fixant certaines variables.
Cette méthode permet de tracer une fonction de plus de deux variables en fixant toutes les variables sauf deux, générant ainsi une surface 3D. Elle effectue automatiquement les vérifications de cohérence.
Paramètres
- plot_varslist of sympy.Symbol, optionnel
Liste de deux variables pour les axes de la surface. Par défaut, les deux premières variables de l’expression.
- fixesdict, optionnel
Dictionnaire {variable: valeur} fixant les autres variables. Par défaut, toutes les autres variables sont fixées à 0.
- **kwargs
Arguments supplémentaires passés à la méthode plot_surface().
Lève
- ValueError
Si plot_vars ne contient pas exactement 2 variables, si les variables de plot_vars n’appartiennent pas à l’expression, si certaines variables ne sont pas fixées, ou si une valeur fixée correspond à une singularité.
Exemples
>>> from sympy.abc import x, y, z, t >>> pex = pxs_Plotable(x**2 + y**2 + z + t) >>> fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) >>> # Surface x-y avec z=1, t=0 >>> pex.plot_surface_partial([x, y], {z: 1, t: 0}) >>> # Surface x-z avec y=0, t=1 >>> pex.plot_surface_partial([x, z], {y: 0, t: 1}, cmap="plasma")
- contour(interv1=Interval(-5, 5), interv2=Interval(-5, 5), nb_points=30, levels=10, title=True, **kwargs)[source]
Trace les lignes de niveau d’une fonction de deux variables.
Cette méthode génère un tracé 2D des courbes de niveau d’une fonction à exactement deux variables.
Paramètres
- interv1pxs_Interval, optionnel
Intervalle pour la première variable. Par défaut [-5, 5].
- interv2pxs_Interval, optionnel
Intervalle pour la deuxième variable. Par défaut [-5, 5].
- nb_pointsint, optionnel
Nombre de points par axe pour la grille. Par défaut 30.
- levelsint ou array-like, optionnel
Nombre de niveaux ou valeurs spécifiques pour les lignes de niveau. Par défaut 10.
- cmapstr, optionnel
Colormap matplotlib pour les lignes de niveau. Par défaut “viridis”.
- titlebool, optionnel
Afficher ou non le titre avec l’expression LaTeX. Par défaut True.
- **kwargs
Arguments supplémentaires passés à matplotlib.pyplot.contour ou contourf.
Lève
- ValueError
Si l’expression ne contient pas exactement deux variables libres.
Exemples
>>> from sympy.abc import x, y >>> import matplotlib.pyplot as plt >>> >>> # Lignes de niveau d'un paraboloïde >>> parab = pxs_Plotable(x**2 + y**2) >>> parab.contour(levels=15) >>> plt.show() >>> >>> # Lignes de niveau avec couleurs personnalisées >>> gaussian = pxs_Plotable(sp.exp(-(x**2 + y**2)/2)) >>> gaussian.contour(cmap="hot", levels=20) >>> >>> # Niveaux spécifiques pour une fonction trigonométrique >>> trig = pxs_Plotable(sp.sin(x)*sp.cos(y)) >>> levels_custom = [-0.8, -0.4, 0, 0.4, 0.8] >>> trig.contour(levels=levels_custom, colors="black", linewidths=2) >>> plt.clabel(cs, inline=True, fontsize=10) # Ajouter des labels >>> >>> # Selle de cheval avec intervalle personnalisé >>> selle = pxs_Plotable(x**2 - y**2) >>> selle.contour(interv1=pxs_Interval(-3, 3), ... interv2=pxs_Interval(-3, 3), ... levels=25, cmap="RdBu_r")
- contour_partial(plot_vars=None, fixes=None, **kwargs)[source]
Trace les lignes de niveau d’une fonction partielle en fixant certaines variables.
Cette méthode permet de tracer les lignes de niveau d’une fonction de plus de deux variables en fixant toutes les variables sauf deux, générant ainsi un tracé 2D de lignes de niveau. Elle effectue automatiquement les vérifications de cohérence.
Paramètres
- plot_varslise de sympy.Symbol, optionnel
Liste de deux variables pour les axes du tracé de contour. Par défaut, les deux premières variables de l’expression.
- fixesdict, optionnel
Dictionnaire {variable: valeur} fixant les autres variables. Par défaut, toutes les autres variables sont fixées à 0.
- **kwargs
Arguments supplémentaires passés à la méthode contour().
Retourne
- matplotlib.contour.QuadContourSet
L’objet contour retourné par matplotlib, utile pour ajouter des labels ou personnaliser l’affichage.
Lève
- ValueError
Si plot_vars ne contient pas exactement 2 variables, si les variables de plot_vars n’appartiennent pas à l’expression, si certaines variables ne sont pas fixées, ou si une valeur fixée correspond à une singularité.
Exemples
>>> from sympy.abc import x, y, z, t >>> import matplotlib.pyplot as plt >>> >>> # Fonction de 4 variables >>> pex = pxs_Plotable(x**2 + y**2 + z*t) >>> >>> # Lignes de niveau dans le plan x-y avec z=1, t=2 >>> pex.contour_partial([x, y], {z: 1, t: 2}, levels=15) >>> >>> # Lignes de niveau dans le plan x-z avec y=0, t=1 >>> pex.contour_partial([x, z], {y: 0, t: 1}, cmap="plasma") >>> >>> # Niveaux personnalisés pour une fonction trigonométrique >>> trig_3d = pxs_Plotable(sp.sin(x)*sp.cos(y) + z) >>> levels_custom = [0, 0.5, 1.0, 1.5, 2.0] >>> trig_3d.contour_partial([x, y], {z: 1}, levels=levels_custom, ... colors="black", linewidths=2)
- plot_corde(absc_corde, fast=False, color='black', linestyle='dashed', marker='.', **kwargs)[source]
Trace la corde reliant deux points d’une courbe.
Cette méthode trace un segment de droite reliant deux points de la courbe représentative de la fonction.
Paramètres
- absc_cordetuple ou list
Tuple ou liste de deux abscisses (a, b) définissant les extrémités de la corde.
- fastbool, optionnel
Mode de tracé rapide utilisant plt directement. Par défaut False.
- colorstr, optionnel
Couleur de la corde. Par défaut “black”.
- linestylestr, optionnel
Style de ligne. Par défaut “dashed”.
- markerstr, optionnel
Marqueur aux extrémités. Par défaut “.”.
- **kwargs
Arguments supplémentaires passés à matplotlib.pyplot.plot.
Lève
- ValueError
Si l’expression ne contient pas exactement une variable libre.
Exemples
>>> from sympy.abc import x >>> pex = pxs_Plotable("x**3 - 2*x") >>> pex.plot(color="blue") >>> # Corde entre x=-1 et x=2 >>> pex.plot_corde((-1, 2), color="red", linewidth=2) >>> # Plusieurs cordes >>> pex.plot_corde((0, 1), color="green", marker="o")
- scatter(n_terms=20, start_index=0, fast=False, **kwargs)[source]
Trace les termes d’une suite numérique sous forme de nuage de points.
Cette méthode évalue l’expression pour des valeurs entières consécutives de la variable et affiche les résultats sous forme de nuage de points.
Paramètres
- n_termsint, optionnel
Nombre de termes de la suite à tracer. Doit être un entier positif. Par défaut 20.
- start_indexint, optionnel
Indice de départ de la suite. Peut être négatif, nul ou positif selon la définition de la suite. Par défaut 0.
- fastbool, optionnel
Mode de tracé rapide utilisant plt directement sans axes personnalisés. Si False, ajoute automatiquement les labels et le titre. Par défaut False.
- **kwargs
Arguments supplémentaires passés à matplotlib.pyplot.scatter. Exemples : color, s (taille), alpha, marker, etc.
Lève
- ValueError
Si l’expression ne contient pas exactement une variable libre. Message : “La fonction scatter ne peut être utilisée que pour des suites (fonction d’une seule variable)”.
Exemples
>>> from sympy.abc import n >>> import matplotlib.pyplot as plt >>> >>> # Suite arithmétique : u_n = 2n + 1 >>> suite1 = pxs_Plotable(2*n + 1) >>> suite1.scatter(n_terms=15, color="blue", s=50) >>> plt.show() >>> >>> # Suite géométrique : u_n = (1/2)^n >>> suite2 = pxs_Plotable("(1/2)**n") >>> suite2.scatter(n_terms=20, start_index=1, color="red", s=40) >>> >>> # Suite alternée : u_n = (-1)^n / n >>> suite4 = pxs_Plotable((-1)**n / n) >>> suite4.scatter(n_terms=20, start_index=1, color="purple", alpha=0.7) >>> >>> # Mode fast pour tracé rapide sans labels >>> suite1.scatter(fast=True, n_terms=10, color="cyan", s=80)
Classes_in_progress
- Classes_in_progress.pxs_config(mul_symbol: str = '') dict[source]
Build a configuration dictionary for LaTeX rendering, depending on the current pyxisciences language settings.
The language is retrieved using get_pxs_lang() and affects some formatting options, such as the decimal separator.
- Parameters:
mul_symbol (str, optional) – Multiplication symbol to be used in LaTeX output (default is “”).
- Returns:
A dictionary containing LaTeX configuration options, including: - ln_notation : bool - mul_symbol : str - order : str - decimal_separator : str - inv_trig_style : str
- Return type:
dict
Examples
>>> pxs_config() {'ln_notation': True, 'mul_symbol': '', 'order': 'lex', ...}
- class Classes_in_progress.NameManager(start='f', skip_letters=('i', 'o', 'x', 'y', 'z'))[source]
- Classes_in_progress.is_simple_linear(expr, variable)[source]
Détecte une expression du type a*x + b ou a*x avec a,b constants (coeffs numériques).
- Classes_in_progress.is_polynomial_in(expr, variable)[source]
Retourne True si expr est un polynôme (coeffs numériques) en ‘variable’.
- Classes_in_progress.pxs_is_reference_function_diff(expr, variable)[source]
Retourne True si expr est une fonction de référence (éventuellement multipliée par une constante). Fonctions de référence : constante, x, x^n, 1/x, sqrt(x), e^x, ln(x), sin(x), cos(x), polynômes simples
- Classes_in_progress.pxs_is_simple_function_diff(expr, variable)[source]
Retourne True si expr est une fonction simple : - fonction de référence - k × fonction de référence - somme de fonctions de référence (avec ou sans coefficients)
- Classes_in_progress.pxs_is_reference_function(expr, variable)[source]
Retourne True si expr est une fonction de référence (éventuellement multipliée par une constante).
- Classes_in_progress.pxs_is_simple(expr, variable)[source]
Détecte une expression du type a*x ou b avec a,b constants (coeffs numériques).
- Classes_in_progress.preserve_order_add(*terms)[source]
Crée une addition en préservant l’ordre des termes.
- Classes_in_progress.split_mul_terms(expr)[source]
Découpe intelligemment un produit en deux facteurs. Si on a -x*f(x), on veut (-x, f(x)) et non (-1, x*f(x))
- Classes_in_progress.should_remove_times(expr)[source]
Détermine si on doit retirer le signe × dans l’expression finale. On retire × pour les cas finaux comme exp, sin, cos avec coefficients.
- Classes_in_progress.narr_conclude_with_details(name, variable, formula_latex, simplified=None, detail=None)[source]
Affiche la conclusion avec la formule détaillée puis la simplification. formula_latex : la formule avec toutes les substitutions simplified : la forme simplifiée (optionnel) - peut être une chaîne LaTeX ou une expression SymPy
- Classes_in_progress.narr_deriv_or_recurse(expr, nm, variable, niveau, lhs=None, func_name=None, detail=None)[source]
Si expr est atomique ou linéaire simple: écrit une équation avec le lhs fourni, sinon descend récursivement via _dispatch_diff. func_name : nom de la fonction à utiliser (si None, on utilise nm.current())
- Classes_in_progress.expliquer_derivation(expr, variable=x, start_name='f', niveau='terminale', detail=None)[source]
- niveau: ‘premiere’ | ‘terminale’
‘premiere’ : on détaille la somme terme à terme, et on explicite k*u
‘terminale’ : polynômes en bloc, pas de détail pour k*u
- class Classes_in_progress.pxs_Add(*args, evaluate=None, _sympify=True)[source]
-
- default_assumptions = {}
- class Classes_in_progress.pxs_Mul(*args, evaluate=None, _sympify=True)[source]
-
- default_assumptions = {}
- class Classes_in_progress.pxs_Pow(b, e, evaluate=None)[source]
-
- is_commutative: bool | None
- default_assumptions = {}
Mes_fctions_d_alg_generale
Created on Thu Mar 17 19:11:52 2022
@author: jlebovits
- Mes_fctions_d_alg_generale.getrandbits(k) x. Generates an int with k random bits.
- Mes_fctions_d_alg_generale.Poly_with_random_coef(symbol, deg, constant_coef)[source]
Returns a list containing: - A polynomial of degree deg in the indeterminate symbol, whose coefficients are randomly and uniformly drawn from the interval [-9, 9].
The constant coefficient is zero if constant_coef equals 0, non-zero if constant_coef equals 1, and randomly drawn from [-9, 9] if constant_coef is neither 0 nor 1. Additionally, the coefficient of the term X^deg is non-zero to ensure that the polynomial is indeed of degree deg.
This polynomial written in TeX with the monomials given in ascending order.
This polynomial written in TeX with the monomials given in descending order.
Mes_fctions_d_alg_lineaire_bis
Created on Thu Mar 17 19:11:52 2022
@author: jlebovits
- Mes_fctions_d_alg_lineaire_bis.pxs_config(mul_symbol: str = '') dict[source]
Build a configuration dictionary for LaTeX rendering, depending on the current pyxisciences language settings.
The language is retrieved using get_pxs_lang() and affects some formatting options, such as the decimal separator.
- Parameters:
mul_symbol (str, optional) – Multiplication symbol to be used in LaTeX output (default is “”).
- Returns:
A dictionary containing LaTeX configuration options, including: - ln_notation : bool - mul_symbol : str - order : str - decimal_separator : str - inv_trig_style : str
- Return type:
dict
Examples
>>> pxs_config() {'ln_notation': True, 'mul_symbol': '', 'order': 'lex', ...}
- Mes_fctions_d_alg_lineaire_bis.pxs_randint(mini, maxi, exclude=[])[source]
Returns a random integer between mini and maxi avoiding the element(s) in exclude. Exclude can be an integer or a collection of integers.
- Mes_fctions_d_alg_lineaire_bis.pxsl_pow(x, n=1, opt=0, displaystyle=True)[source]
Fr : Fonction permettant d’écrire le nombre x entouré de parenthèses lorsqu’il est négatif ou irrationnel avec deux termes (par ex : 1+sqrt(2) ou 3sqrt(2)) Ne fonctionne pas pour des valeurs numériques non simplifiées (par ex : 1+3 ou 3*3/2) En : Function that writes the number x surrounded by parentheses when it is negative or irrational with two terms (e.g.: 1+sqrt(2) or 3sqrt(2)) Does not work for unsimplified numerical values (e.g.: 1+3 or 3*3/2)
Version 5
13/02/25
Vérification
Auteur : Delphine Vérificateurs : ??
Paramètres
- xnombre ou expression
La base à élever à la puissance n
- nint, optional
L’exposant (défaut: 1)
- optint, optional
Option de formatage (défaut: 0) 0: formatage standard 1: simplifie l’affichage pour x=1, x=0 ou n=1 2: simplifie davantage et renvoie une chaîne vide pour x=0
- displaystylebool, optional
Si True, utilise displaystyle pour les fractions (défaut: False)
Retour
- str
retourne l’expression en latex
Fonction utilisée par
pxsl_sum_matrix, pxsl_prod_scalar_matrix, pxsl_prod_matrix, pxsl_pow_matrix
- Mes_fctions_d_alg_lineaire_bis.pxsl_matrix(A, sepG='(', sepD=')', display=False, res_num=False)[source]
Return a LaTeX representation of a matrix with right-aligned entries.
This function converts a matrix into a nicely formatted LaTeX matrix. By default, entries are displayed as raw values. Optional display modes allow symbolic LaTeX rendering or numerical result formatting.
- Parameters:
A (Matrix) – The matrix to be displayed.
sepG (str, optional) – Left delimiter of the matrix (default “(“). In English mode, it is automatically replaced by “[“.
sepD (str, optional) – Right delimiter of the matrix (default “)”). In English mode, it is automatically replaced by “]”.
display (bool, optional) – If True, matrix entries are rendered in LaTeX format.
res_num (bool, optional) – If True (and display=True), entries are displayed as numerical results.
- Returns:
A LaTeX string representing the formatted matrix.
- Return type:
str
Examples
Basic usage with raw values:
>>> from sympy import Matrix >>> A = Matrix([[1, 2], [3, 4]]) >>> pxsl_matrix(A) '\\left(\begin{array}{rr}1 & 2\\[0.3em]3 & 4\end{array}\\right)'
Using custom delimiters:
>>> pxsl_matrix(A, sepG='[', sepD=']') '\\left[\begin{array}{rr}1 & 2\\[0.3em]3 & 4\end{array}\\right]'
Displaying symbolic expressions in LaTeX:
>>> from sympy import symbols >>> x = symbols('x') >>> B = Matrix([[x, x**2], [1/x, 2]]) >>> pxsl_matrix(B, display=True) '\\left(\begin{array}{rr}x & x^{2}\\[0.3em]\frac{1}{x} & 2\end{array}\\right)'
Displaying numerical results (after evaluation):
>>> from sympy import Rational >>> C = Matrix([[Rational(1, 2), Rational(3, 4)], [1, 2]]) >>> pxsl_matrix(C, display=True, res_num=True) '\\left(\begin{array}{rr}0.5 & 0.75\\[0.3em]1 & 2\end{array}\\right)'
- Mes_fctions_d_alg_lineaire_bis.pxsl_mat(A, sepG='(', sepD=')', display=False, frac=False, res_num=False, color='blue', row='', col='', union=True, order=True, dec=4)[source]
Return a LaTeX representation of a SymPy matrix.
The function converts the entries of a matrix into a LaTeX array enclosed between customizable delimiters. It can display entries in normal mode, display mode, fractional LaTeX form, numerical approximation, and can highlight a row, a column, or their intersection.
- Parameters:
A (sympy.Matrix) – Matrix to be converted into LaTeX.
sepG (str, optional) – Left delimiter. Default is
"(". In English mode, the default parenthesis is automatically replaced by"[".sepD (str, optional) – Right delimiter. Default is
")". In English mode, the default parenthesis is automatically replaced by"]".display (bool, optional) – If
True, each entry is written in display style using\ds. This is useful for entries containing fractions, sums, powers, or other expressions that are more readable in display mode. Default isFalse.frac (bool, optional) – If
True, entries are rendered using SymPy’slatexfunction. This is useful when entries are rational numbers or symbolic expressions. Default isFalse.res_num (bool, optional) – If
True, entries are rendered as numerical approximations usingpxsl_num. This option has priority overdisplayandfrac. Default isFalse.color (str, optional) – LaTeX color used to highlight selected entries. Default is
"blue".row (int or str, optional) – Index of the row to highlight. Row indices start at
0. If no row should be highlighted, keep the default value"".col (int or str, optional) – Index of the column to highlight. Column indices start at
0. If no column should be highlighted, keep the default value"".order (bool, optional) – If True, the order of the terms is preserved when coefficients are litteral expressions. Default is True
union (bool, optional) –
Determines how
rowandcolare combined when both are given.If
True, all entries in the selected row or in the selected column are highlighted.If
False, only the entry at the intersection of the selected row and selected column is highlighted.
Default is
True.
- Returns:
A LaTeX string representing the matrix.
- Return type:
str
Examples
Basic matrix with default delimiters:
>>> from sympy import Matrix >>> A = Matrix([[1, 2], [3, 4]]) >>> pxsl_matrix(A) '\left(\begin{array}{rr} 1 & 2\\[6pt] 3 & 4\\[6pt]\end{array}\right)'
Use custom delimiters:
>>> pxsl_matrix(A, sepG="[", sepD="]") '\left[\begin{array}{rr} 1 & 2\\[6pt] 3 & 4\\[6pt]\end{array}\right]'
Display fractions using LaTeX formatting:
>>> from sympy import Rational >>> B = Matrix([[Rational(1, 2), Rational(2, 3)], [Rational(3, 4), 1]]) >>> pxsl_matrix(B, frac=True) '\left(\begin{array}{rr}\frac{1}{2} & \frac{2}{3}\\[6pt]\frac{3}{4} & 1\\[6pt]\end{array}\right)'
Use display style for larger entries:
>>> pxsl_matrix(B, display=True) '\left(\begin{array}{rr}\ds \frac{1}{2} &\ds \frac{2}{3}\\[10pt]\ds \frac{3}{4} &\ds 1\\[10pt]\end{array}\right)'
Display numerical approximations:
>>> pxsl_matrix(B, res_num=True) '\left(\begin{array}{rr}0.5 & 0.67\\[6pt]0.75 & 1\\[6pt]\end{array}\right)'
Highlight a row:
>>> pxsl_matrix(A, row=1) '\left(\begin{array}{rr} 1 & 2\\[6pt] \textcolor{blue}{3} &\textcolor{blue}{4}\\[6pt]\end{array}\right)'
Highlight a column:
>>> pxsl_matrix(A, col=0, color="red") '\left(\begin{array}{rr} \textcolor{red}{1} & 2\\[6pt] \textcolor{red}{3} & 4\\[6pt]\end{array}\right)'
Highlight the union of a row and a column:
>>> pxsl_matrix(A, row=0, col=1, color="purple", union=True) '\left(\begin{array}{rr}\textcolor{purple}{1} &\textcolor{purple}{2}\\[6pt] 3 &\textcolor{purple}{4}\\[6pt]\end{array}\right)'
Highlight only the intersection of a row and a column:
>>> pxsl_matrix(A, row=0, col=1, color="purple", union=False) '\left(\begin{array}{rr} 1 &\textcolor{purple}{2}\\[6pt] 3 & 4\\[6pt]\end{array}\right)'
Notes
The priority order for rendering entries is:
res_num=True: numerical approximation withpxsl_num;display=True: LaTeX display style with\ds;frac=True: LaTeX formatting with SymPy’slatex;otherwise: raw entry display.
Row and column indices start at
0.
- Mes_fctions_d_alg_lineaire_bis.pxsl_sum_matrix(A, B, s='+', sepG='(', sepD=')')[source]
Fonction permettant d’afficher le détail de la somme (ou la différence) de deux matrices
Version
13/02/25
Vérification
Auteur : Ronan - Delphine Vérificateurs :
Paramètres
- AMatrix
Première matrice de la somme
- BMatrix
Deuxième matrice de la somme
- sstr
“+” par défaut pour réaliser une somme “-” pour réaliser une différence
- sepGstr
délimiteur gauche de la matrice
- sepDstr
délimiteur droit de la matrice
Retour
- str
retourne l’expression en latex
Fonction utilisée par
aucune fonction pyxiscience
- Mes_fctions_d_alg_lineaire_bis.pxsl_prod_scalar_matrix(lamb, A, mult='times', sepG='(', sepD=')')[source]
Fonction permettant d’afficher le détail du produit entre un scalaire et une matrice
Version
13/02/25
Vérification
Auteur : Ronan - Delphine Vérificateurs :
Paramètres
- lambfloat
coefficient multiplicateur
- AMatrix
Matrice
- multstr
“times” par défaut, peut-être remplacé par “cdot” pour modifier le symbole multiplicatif
- sepGstr
délimiteur gauche de la matrice
- sepDstr
délimiteur droit de la matrice
Retour
- str
retourne l’expression en latex
Fonction utilisée par
aucune fonction pyxiscience
- Mes_fctions_d_alg_lineaire_bis.pxsl_prod_matrix(A, B, mult='times', sepG='(', sepD=')')[source]
Fonction permettant d’afficher le détail du produit entre deux matrices
Version
13/02/25
Vérification
Auteur : Ronan - Delphine Vérificateurs :
Paramètres
- AMatrix
Première matrice du produit
- BMatrix
Deuxième matrice du produit
- multstr
“times” par défaut, peut-être remplacé par “cdot” pour modifier le symbole multiplicatif
- sepGstr
délimiteur gauche de la matrice
- sepDstr
délimiteur droit de la matrice
Retour
- str
retourne l’expression en latex
Fonction utilisée par
aucune fonction pyxiscience
- Mes_fctions_d_alg_lineaire_bis.pxs_system_simpl(n=3, N='', opt='sys', max_coef=2, limit_sum=15)[source]
Fonction permettant de créer les matrices A et B d’un système linéaire en s’assurant de la simplicité de la solution Par défaut, la matrice est de taille 3x3 et B un vecteur aléatoire, de composant entre 1 et 3, de dimension 3 La fonction est également utilisable pour générer A dans le cadre de l’inversion de matrice
Version
25/03/25
Vérification
Auteur : Delphine Vérificateurs :
Paramètres
- nint
Dimension de la matrice A
- NMatrix
Deuxième matrice du produit, solution du système
- optchar
“sys” : c’est un système, on renvoie A et B pour Ax=B sinon : on renvoie seulement A
- max_coefint
on tire les opérations à réaliser sur les coefficients entre 1 et max_coef
- limit_sumint
si les coefficients de A et B dépassent la valeur de limit_sum la simulation est relancée
Retour
- A,B
retourne les deux matrices du système AX=B
Fonction utilisée par
pxs_commute_matrix
- Mes_fctions_d_alg_lineaire_bis.pxsl_ax(a, x=x, sign=' ', frac=True)[source]
Fonction permettant d’afficher l’expression ax en fonction des valeurs de a
Version
23/09/25
Vérification
Auteur : Delphine Vérificateurs :
Paramètres
a : numerique x : Symbol (‘x’ par défaut)
si x=Symbol(“val”), la valeur a est affichée dans tous les cas
- signstr
“” ou “+”, “” par défaut, le symbole “+” indique qu’il faut écrire le signe ‘+’ devant l’expression.
- fracboolean
True : fraction écrite en mode math False : fraction écrite a/b en ligne
Retour
- str
retourne l’expression en latex
Fonction utilisée par
pxsl_system_lin, pxsl_lines_op
- Mes_fctions_d_alg_lineaire_bis.pxsl_double_matrix(A, B, listeMat=[], opt='sep', display=False)[source]
Fonction permettant d’afficher un système linéaire Ax=B
Version
13/02/25
Vérification
Auteur : Delphine Vérificateurs :
Paramètres
A : Matrix B : Matrix listeMat : liste
permet d’envisager l’ajout de matrices supplémentaires
- optstr (‘sep’ par défaut)
permet de préciser la présentation des matrices ‘sep’ : les deux matrices sont présentées côte à côte entourées de parenthèses ‘ext’ : les deux matrices sont présentées en matrice étendue séparée par
Retour
- str
retourne l’expression en latex
Fonction utilisée par
pxsl_resol_system
- Mes_fctions_d_alg_lineaire_bis.pxsl_system_lin(A, B, x='x', frac=True)[source]
Construct a LaTeX representation of a linear system.
The function formats a linear system of equations defined by a coefficient matrix A and a right-hand side vector B into a LaTeX array environment. Each equation is written as a linear combination of symbolic variables followed by its corresponding constant term.
- Parameters:
A (Matrix) – Coefficient matrix of the linear system.
B (Matrix) – Right-hand side vector of the system.
x (str, optional) – Base name of the unknown variables (default is “x”), producing variables of the form x_1, x_2, …, x_n.
frac (bool, optional) – If True, coefficients are displayed as fractions when appropriate. If False, coefficients are displayed in a simplified inline form.
- Returns:
A symbolic object representing the LaTeX code of the linear system formatted as an array.
- Return type:
Any
Examples
>>> pxsl_system_lin(A, B) '\\left\{ \\begin{array}{rcl} ... \\end{array}\\right.'
- Mes_fctions_d_alg_lineaire_bis.pxsl_lines_op(n, listOp, opt='sys', frac=True)[source]
Construct a LaTeX array describing elementary row (line) operations.
The function generates a symbolic LaTeX representation of a sequence of elementary row operations applied to a system or a matrix. Each operation is displayed line by line using an array environment, with arrows and linear combinations formatted according to the current language settings (French or English).
- Parameters:
n (int) – Number of rows of the system or matrix.
listOp (list) –
List of elementary row operations. Each element of the list is expected to be a tuple of the form (a, i, b, j) representing an operation applied to row i using row j: - if a == 0, rows i and j are swapped; - otherwise, the operation corresponds to
row_i ← a * row_i + b * row_j.
Row indices are assumed to be 1-based.
opt (str, optional) – Output option (currently kept for interface consistency; default is “sys”).
frac (bool, optional) – If True, coefficients are displayed as fractions when appropriate. If False, coefficients are displayed in a simplified inline form.
- Returns:
A symbolic object representing the LaTeX code of an array environment describing the row operations.
- Return type:
Any
Examples
>>> pxsl_lines_op( ... n=3, ... listOp=[(1, 1, -2, 2), (0, 2, 1, 3)] ... ) '\\begin{array}{ccc} ... \\end{array}'
- Mes_fctions_d_alg_lineaire_bis.pxsl_resol_system(listA, listB=[], listOp=[], x='x', method='sys', view='sep', detail='on')[source]
Fonction qui permet d’écrire chaque étape de la résolution d’un problème impliquant des manipulations de lignes
Version
23/09/25
Vérification
Auteur : Ronan - Delphine Vérificateurs :
Paramètres
- listAlist
contient la liste des matrices A successives utilisées lors de la résolution
- listBlist
contient la liste des vecteurs (système) ou matrice (inversion) B successives utilisées lors de la résolution
- listOpliste de liste
chaque liste de la liste contient 4 éléments [a, ind1,b,ind2] permettant de réaliser le calcul sur la ligne d’indice ind1 a*L_ind1+b*L_ind2
- xs.Symbol (‘x’ par défaut)
utilisé comme variable dans le cas de la résolution d’un système
- methodstr (‘sys’ par défaut)
“sys” : résolution d’un système “mat” : inversion d’une matrice “ech” : échelonnage d’une matrice
- viewstr (“sep” par défaut)
“sep” : les deux matrices sont représentées côte à côté “ext” : représente la matrice étendue A|B
Retour
- str
retourne l’expression en latex
Fonction utilisée par
Aucune fonction pyxiscience
- Mes_fctions_d_alg_lineaire_bis.pxs_reduce_pgcd(A, B, listA, listB, listOp)[source]
Fonction permettant de diviser lignes des matrices A et B lorsque leur pgcd est différent de 1
Version
23/09/25 (modifié 14/10/25)
Vérification
Auteur : Delphine Vérificateurs : Paramètres ———- A : Matrix B : Matrix listA : list
liste de matrices, permet de retrouver les différentes transformations de la matrice A
- listBlist
liste de matrices, permet de retrouver les différentes transformations de la matrice B
- listOplist
Chaque élément de la liste est une liste de 4 éléments : [facteur multiplicatif de la ligne i, indice de la ligne i, facteur multiplicatif de la ligne j, indice de la ligne j]
Retour
- liste, liste, liste
retourne les listes actualisées de l’opération de permutation
Fonction utilisée par
pxs_steps_invert_matrix
- Mes_fctions_d_alg_lineaire_bis.pxs_steps_invert_matrix(A, B, x='x', method='sys', view='sep', detail='on')[source]
Fonction permettant de stocker toutes les étapes de la résolution d’un système ou l’inversion d’une matrice
Version
23/09/25
Vérification
Auteur : Ronan - Delphine Vérificateurs :
Paramètres
A : Matrix B : Matrix x : Symbol (‘x’ par défaut)
liste de matrices, permet de retrouver les différentes transformations de la matrice A
- methodstr
“sys” : pour afficher la résolution d’un système
- listOplist
Chaque élément de la liste est une liste de 4 éléments : [facteur multiplicatif de la ligne i, indice de la ligne i, facteur multiplicatif de la ligne j, indice de la ligne j]
Retour
- liste, liste, liste
retourne les listes actualisées de l’opération de permutation
Fonction utilisée par
Aucune fonction pyxiscience
- Mes_fctions_d_alg_lineaire_bis.pxs_LU_decomposition(A, view='sep', detail='on', name_matrix=' ', PLU=False)[source]
Details the steps of LU factorization for a square matrix A.
Version
26/12/25
- Mes_fctions_d_alg_lineaire_bis.pxs_matrix_no_LU(p, no_first=True)[source]
Constructs a random sympy (p x p) matrix with integer coefficients, for which the LU decomposition without pivoting does not exist.
Strategy: a random index k is chosen in {1, …, p-1}, then the k-th leading principal submatrix A_k is made singular by replacing its last row with a linear combination of the k-1 previous rows. Coefficients of the full matrix are drawn from [-5, 5], except for the constructed row which may exceed these bounds.
- Parameters:
p (int) – Matrix size (must be >= 2).
no_first (True for avoiding a 0 as first coefficient)
- Returns:
A sympy (p x p) matrix with no LU decomposition.
- Return type:
Matrix
- Mes_fctions_d_alg_lineaire_bis.pxsl_print_operations(list_mat, listOp=[], method='sys', x='x', view='sep', detail='on', frac=True)[source]
Displays each step of the resolution for a problem involving line operations. This function is meant to replace pxsl_resol_system
Version
06/01/26
Authors
Auteur : Ronan - Delphine - Raphaël Vérificateurs :
- param list_mat:
each element is a list of successive matrices appearing in the resolution
- type list_mat:
list of lists
- param listOp:
- each sublist contains 4 elements [a, ind1, b, ind2] describing the following operation:
L(ind1) <- a * L_ind1 + b * L_ind2
- type listOp:
liste of lists
- param x:
determines the name of the variables in the system
- type x:
s.Symbol (‘x’ par défaut)
- param method:
“sys” : system form “mat” : matrix form
- type method:
str (‘sys’ by default)
- param view:
“sep” : matrices are displayed side-by-side “ext” : extended matrix A1|A2|…|An
- type view:
str (“sep” by default)
- param frac:
If True, coefficients are displayed as fractions when appropriate. If False, coefficients are displayed in a simplified inline form.
- type frac:
bool, optional
- returns:
str – Latex expression
Function used by
———————
pxs_steps_invert_matrix, pxs_LU_decomposition, pxs_compute_ech, pxs_compute_ech_reduite
- Mes_fctions_d_alg_lineaire_bis.pxs_commute_matrix(n, opt='')[source]
Fonction permettant de créer les matrices A, B et C de dimension n avec A et B commutantes et A et C non commutantes
Version
13/02/25
Vérification
Auteur : Ronan - Delphine Vérificateurs :
Paramètres
- nint
Dimension de la matrice A
- opt: str
“commut” : Envoie deux matrices qui commutent “noncommut” : Envoie deux matrices qui ne commutent pas autre : renvoie les trois matrices
Retour
- A,B
retourne les deux matrices du système AX=B
Fonction utilisée par
aucune fonction pyxiscience
- Mes_fctions_d_alg_lineaire_bis.pxsl_pow_matrix(A, k, opt=0, sepG='(', sepD=')')[source]
Fonction permettant d’écrire en latex une matrice dont tous les coefficients sont élevés à la même puissance Les puissances de 0 et 1 sont simplifiées, les valeurs sont centrées par défaut
Version
13/02/25
Vérification
Auteur : Ronan - Delphine Vérificateurs :
Paramètres
A : Matrix k : float ou Symbol
valeur de la puissance
- sepGstr
délimiteur gauche de la matrice
- sepDstr
délimiteur droit de la matrice
Retour
- str
retourne l’expression en latex
Fonction utilisée par
aucune fonction pyxiscience
- Mes_fctions_d_alg_lineaire_bis.pxs_regroupe_ligne(list_mat, listOp=[])[source]
Fonction permettant de regrouper les lignes qui peuvent être écrites en une seule étape
Version
21/03/25 -> 06/01/26 (Raphaël)
Vérification
Auteur : Delphine Vérificateurs :
Paramètres
- listAlist
liste des étapes pour la matrice/système de départ
- listBlist
liste des étapes pour la matrice miroir (inversion) ou membre droit (système)
- listOpliste
liste des opérations sur lignes
Retour
- listA, listB, listOp
retourne les listes actualisées
Fonction utilisée par
pxsl_resol_system, pxsl_print_operations
- Mes_fctions_d_alg_lineaire_bis.pxs_compute_ech(A)[source]
Fonction permettant de stocker toutes les étapes de la construction d’une matrice échelonnée
Paramètres
A : Matrix
Retour
- liste, liste, liste
retourne les listes actualisées de l’opération de permutation
Fonction utilisée par
Aucune fonction pyxiscience
- Mes_fctions_d_alg_lineaire_bis.pxs_compute_ech_reduite(A)[source]
Fonction transformant une matrice en forme échelonnée réduite en stockant chaque étape.
Paramètres
- Anumpy.ndarray
Matrice d’entrée
Retour
listA : liste des matrices à chaque étape listOp : liste des opérations sous forme [a, i, b, j] avec :
a : coefficient multiplicatif pour L_i
i : numéro de la ligne affectée (1-based index)
b : coefficient multiplicatif pour L_j
j : numéro de la ligne utilisée (1-based index)
- Mes_fctions_d_alg_lineaire_bis.randmatrixrect(p, q, a, b)[source]
Returns a rectangular matrix with p rows and q columns such that every coefficient is a realization of of a discrete random variable on range(a, b)
- returns:
LaTeX bmatrix as a string
- Mes_fctions_d_alg_lineaire_bis.pxs_diag_matrix(p, a, b)[source]
Returns a square diagonal matrix of size p such that every coefficient is a realization of a uniform discrete random variable, the range of which is range(a, b)
- Mes_fctions_d_alg_lineaire_bis.pxs_triangular(p, a, b, diag=None, lower=False, inv=False)[source]
Returns a square triangular matrix of size p such that every coefficient is a realization of a uniform discrete random variable, the range of which is [[a, b]] The diagonal coefficients can be specified as a list with the optional <diag> argument.
- Mes_fctions_d_alg_lineaire_bis.pxs_construct_RREF(n=3, p=3, M=(1, 2, 3), min=-9, max=9)[source]
Construct a matrix with a partial Row Reduced Echelon Form (RREF) structure based on a given pivot pattern.
The function creates a matrix of shape (n, p) whose pivot positions are specified by the tuple M. Each element m of M indicates that the corresponding row has a pivot equal to 1 in column m-1. The remaining coefficients located to the right of the pivot and outside the pivot columns are filled with random integers between min and max.
- Parameters:
n (int, optional) – Number of rows of the matrix (default is 3).
p (int, optional) – Number of columns of the matrix (default is 3).
M (tuple or Matrix, optional) –
If M is a tuple, it represents the pivot positions (1-based indexing).
If M is a SymPy Matrix, it is copied and used as the initial matrix.
min (int, optional) – Minimum value for the random coefficients (default is -9).
max (int, optional) – Maximum value for the random coefficients (default is 9).
- Returns:
A SymPy matrix of shape (n, p) that follows the structure imposed by M.
- Return type:
Matrix
Examples
>>> pxs_construct_RREF(n=3, p=4, M=(1, 3)) Matrix([ [1, 0, 0, a], [0, 0, 1, b], [0, 0, 0, 0] ])
>>> pxs_construct_RREF(n=2, p=3, M=(2,)) Matrix([ [0, 1, c], [0, 0, 0] ])
- Mes_fctions_d_alg_lineaire_bis.pxs_generate_sys(M=(1, 2, 3), n=3, p=3, N='', opt='sys', min=-9, max=9)[source]
Generate a linear system associated with a matrix in (partial) RREF form.
The function first constructs a matrix with a Row Reduced Echelon Form–like structure using pxs_construct_RREF, based on the pivot pattern M. A right-hand side vector is generated (or copied) and a simplifying transformation matrix is then applied to produce either the full linear system or only the transformed coefficient matrix.
- Parameters:
M (tuple or Matrix, optional) –
If M is a tuple, it specifies the pivot positions (1-based indexing) used to construct the RREF-like matrix.
If M is a SymPy Matrix, its shape defines the values of n and p.
n (int, optional) – Number of rows of the system (default is 3).
p (int, optional) – Number of columns of the coefficient matrix (default is 3).
N (Matrix or str, optional) – Right-hand side vector of the system. If an empty string is provided, a random vector of length n with integer entries between -3 and 3 is generated.
opt (str, optional) –
Output option: - “sys” returns both the transformed coefficient matrix and the
transformed right-hand side vector.
Any other value returns only the transformed coefficient matrix.
min (int, optional) – Minimum value for the random coefficients in the generated matrix (default is 9).
max (int, optional) – Maximum value for the random coefficients in the generated matrix (default is 9).
- Returns:
If opt == “sys”, returns a tuple (A, B) where A is the transformed coefficient matrix and B is the transformed right-hand side vector.
Otherwise, returns only the transformed coefficient matrix.
- Return type:
Matrix or tuple of Matrix
Examples
>>> A, B = pxs_generate_sys(M=(1, 3), n=3, p=4) >>> A.shape (3, 4)
>>> A = pxs_generate_sys(M=(2,), n=2, p=3, opt="mat") >>> A.shape (2, 3)
- Mes_fctions_d_alg_lineaire_bis.pxs_repeat_generate_sys(M=(1, 2, 3), n=3, p=3, N='', opt='sys', min=-9, max=9, backup=Matrix([[1, 1, 1], [1, 2, 3], [2, 3, 4]]), nb_iter=10)[source]
- Mes_fctions_d_alg_lineaire_bis.pxs_gauss_jordan(A, B=None, x: str = 'x', method: str = 'sys', view: str = 'sep', detail: str = 'on', strict: bool = False, frac: bool = True, vectors: str = 'col', short: bool = True)[source]
Perform a Gauss–Jordan elimination and generate a formatted (LaTeX) output of all intermediate steps.
The function applies the Gauss–Jordan algorithm to the linear system
A * X = B(or to the reduction ofAalone ifB is None). Each elementary row operation is recorded so that a detailed, step-by-step symbolic representation of the reduction process can be produced, typically for inclusion in a LaTeX document via themyst/pxsl_*utilities.- Parameters:
A (Matrix) – Coefficient matrix of the linear system (SymPy
Matrix).B (Matrix or None, optional) – Right-hand side vector or matrix. If
None, the function only reducesA(the right-hand side is taken as a zero matrix of compatible size).x (str, optional) – Base name of the unknown variables used in the symbolic display (e.g.
"x"producesx_1, x_2, ...). Default is"x".method (str, optional) – Display method passed to the printing routine (typically
"sys"to format the output as a linear system). Default is"sys".view (str, optional) – Visualization mode for intermediate steps (for example, separate or combined views of matrices and operations). Default is
"sep".detail (str, optional) –
Level of detail in the output: -
"on"displays all elementary operations, - other values may reduce verbosity (depending onpxsl_print_operations).Default is
"on".strict (bool, optional) –
Pivot selection strategy: - if
True, applies a strict Gauss–Jordan strategy by choosing, belowthe current row, the pivot with the largest absolute value in the column (partial pivoting);
if
False, chooses the first non-zero coefficient below the current row (simplified strategy).
Default is
False.frac (bool, optional) – Controls the rendering of rational coefficients: - if
True, coefficients are displayed as fractions when appropriate, - ifFalse, coefficients may be displayed in a simplified inline form. Default isTrue.vectors (str, optional) – Orientation of solution vectors in the display: -
"col"for column vectors, - any other value for row vectors. Default is"col".
- Returns:
A symbolic object representing the formatted output (typically a LaTeX string or structure produced via
mystandpxsl_*utilities).- Return type:
Any
Examples
Basic example (solving a square linear system):
>>> from sympy import Matrix >>> A = Matrix([[1, 2], [3, 4]]) >>> B = Matrix([[5], [6]]) >>> out = pxs_gauss_jordan(A, B) >>> isinstance(out, str) or out is not None True
Changing the variable base name (
x="u"producesu_1, u_2, ...):>>> A = Matrix([[1, 1], [0, 1]]) >>> B = Matrix([[2], [3]]) >>> out = pxs_gauss_jordan(A, B, x="u") >>> isinstance(out, str) or out is not None True
Pivot strategy: simplified vs strict (partial pivoting):
>>> A = Matrix([[0, 1], [2, 3]]) >>> B = Matrix([[1], [1]]) >>> out1 = pxs_gauss_jordan(A, B, strict=False) # first non-zero pivot >>> out2 = pxs_gauss_jordan(A, B, strict=True) # largest |value| pivot >>> (out1 is not None) and (out2 is not None) True
Reducing verbosity (if supported by the display routine):
>>> A = Matrix([[1, 2], [3, 4]]) >>> B = Matrix([[5], [6]]) >>> out = pxs_gauss_jordan(A, B, detail="off") >>> out is not None True
Skipping the final solution display (only reduction steps):
>>> A = Matrix([[1, 2], [3, 4]]) >>> B = Matrix([[5], [6]]) >>> out = pxs_gauss_jordan(A, B, solve=False) >>> out is not None True
Reducing
Aalone (B=None):>>> A = Matrix([[1, 2, 3], [2, 4, 6]]) >>> out = pxs_gauss_jordan(A) >>> out is not None True
Solution set representation (vector orientation and span form):
>>> A = Matrix([[1, 1, 0], [0, 0, 1]]) >>> B = Matrix([[2], [3]]) >>> out_col = pxs_gauss_jordan(A, B, vectors="col", span=True) >>> out_row = pxs_gauss_jordan(A, B, vectors="row", span=False) >>> (out_col is not None) and (out_row is not None) True
- Mes_fctions_d_alg_lineaire_bis.pxs_colinear_rows(M, i, j)[source]
Test whether two rows of a matrix are colinear.
Two rows are said to be colinear if one is a scalar multiple of the other. The test is performed by computing the rank of the matrix formed by the two rows.
By convention, if at least one of the two rows is a zero row, the function returns
False(zero rows are ignored).- Parameters:
M (Matrix) – A SymPy matrix.
i (int) – Index of the first row to test (0-based).
j (int) – Index of the second row to test (0-based).
- Returns:
Trueif rowsiandjare colinear,Falseotherwise.- Return type:
bool
Examples
Two proportional rows:
>>> from sympy import Matrix >>> M = Matrix([[1, 2, 3], ... [2, 4, 6], ... [1, 0, 1]]) >>> pxs_colinear_rows(M, 0, 1) True
Rows that are not colinear:
>>> pxs_colinear_rows(M, 0, 2) False
A zero row is ignored:
>>> M = Matrix([[1, 2, 3], ... [0, 0, 0], ... [2, 4, 6]]) >>> pxs_colinear_rows(M, 0, 1) False
Colinearity still detected with non-adjacent rows:
>>> pxs_colinear_rows(M, 0, 2) True
- Mes_fctions_d_alg_lineaire_bis.pxs_break_colinearity(M, N, i, j, *, coef_range=(-3, 3))[source]
Break the colinearity between two rows of a linear system using an elementary row operation.
If rows
iandjof the matrixMare colinear, the function replaces rowiby a linear combinationrow_i ← a * row_i + b * row_k
where
kis a row index different fromiandj, andaandbare nonzero integers chosen randomly incoef_range.The same operation is applied consistently to the right-hand side vector
Nso that the linear system remains equivalent.If rows
iandjare not colinear, or if no suitable third row is available, the matrices are returned unchanged.- Parameters:
M (Matrix) – Coefficient matrix of the linear system.
N (Matrix) – Right-hand side column vector of the system.
i (int) – Index of the first row (0-based).
j (int) – Index of the second row (0-based).
coef_range (tuple of int, optional) – Range
(min, max)from which the integer coefficientsaandbare drawn (default is(-3, 3)). Zero is excluded.
- Returns:
Matrix – The modified coefficient matrix.
Matrix – The modified right-hand side vector.
Examples
Breaking colinearity between two proportional rows:
>>> from sympy import Matrix >>> M = Matrix([[1, 2, 3], ... [2, 4, 6], ... [1, 0, 1]]) >>> N = Matrix([1, 2, 0])
>>> M2, N2 = pxs_break_colinearity(M, N, 0, 1)
The resulting system is equivalent, but rows 0 and 1 are no longer colinear:
>>> from sympy import Matrix >>> Matrix([M2.row(0), M2.row(1)]).rank() == 1 False
If the rows are not colinear, nothing is changed:
>>> M = Matrix([[1, 2], ... [3, 4]]) >>> N = Matrix([1, 1]) >>> M2, N2 = pxs_break_colinearity(M, N, 0, 1) >>> M2 == M and N2 == N True
If no suitable third row exists, the matrices are returned unchanged:
>>> M = Matrix([[1, 2], ... [2, 4]]) >>> N = Matrix([1, 2]) >>> M2, N2 = pxs_break_colinearity(M, N, 0, 1) >>> M2 == M and N2 == N True
- Mes_fctions_d_alg_lineaire_bis.pxs_break_all_colinear_rows(A, B, max_iter=5)[source]
Remove colinearity between all pairs of rows of a linear system.
The function repeatedly scans the coefficient matrix
Afor pairs of colinear rows. Whenever such a pair is found, an elementary row operation is applied (viapxs_break_colinearity()) to break the colinearity while preserving the solution set of the system.The process is repeated until no colinear row pairs remain, or until the maximum number of iterations is reached.
- Parameters:
A (Matrix) – Coefficient matrix of the linear system.
B (Matrix) – Right-hand side column vector.
max_iter (int, optional) – Maximum number of iterations allowed to remove colinearities (default is
10).
- Returns:
Matrix – The modified coefficient matrix with reduced row colinearity.
Matrix – The modified right-hand side vector.
Examples
Removing colinearity between multiple rows:
>>> from sympy import Matrix >>> A = Matrix([[1, 2, 3], ... [2, 4, 6], ... [3, 6, 9]]) >>> B = Matrix([1, 2, 3])
>>> A2, B2 = pxs_break_all_colinear_rows(A, B)
After processing, no two nonzero rows are colinear:
>>> any( ... Matrix([A2.row(i), A2.row(j)]).rank() == 1 ... for i in range(A2.rows) ... for j in range(i + 1, A2.rows) ... if not A2.row(i).is_zero and not A2.row(j).is_zero ... ) False
If the matrix contains no colinear rows, it is returned unchanged:
>>> A = Matrix([[1, 0], ... [0, 1]]) >>> B = Matrix([1, 1]) >>> A2, B2 = pxs_break_all_colinear_rows(A, B) >>> A2 == A and B2 == B True
- Mes_fctions_d_alg_lineaire_bis.pxs_zero_column(A)[source]
Checks whether Matrix A has at least one zero column.
- Parameters:
A (Matrix)
- Returns:
bool
- Return type:
True if A has at least one zero column, False otherwise
Examples
>>> A = Matrix( ... [[1, 0, 2], ... [2, 0, -3], ... [1, 0, 1]]) >>> pxs_zero_column(A) True
>>> M = Matrix( ... [[1, 0, 2], ... [2, 1, -3], ... [1, 0, 1]]) >>> pxs_zero_column(M) False
- Mes_fctions_d_alg_lineaire_bis.pxs_determinant(A, detail='on', **kwargs)[source]
Compute the determinant of a matrix using row reduction, with optional step-by-step output.
The function reduces the matrix to upper-triangular form via row swaps and row scaling, tracking all intermediate matrices and operations. The determinant is then recovered from the diagonal of the final matrix, the number of row swaps performed, and the scaling factors applied.
- Parameters:
A (Matrix) – A square SymPy matrix.
detail (str, optional) – If
"on"(default), row operations are displayed next to each intermediate matrix. Any other value suppresses the operation labels.**kwargs – Additional keyword arguments forwarded to SymPy’s
latex()function (e.g.mul_symbol).
- Returns:
A dictionary with the following keys:
"last"MatrixThe final row-reduced matrix.
"oper"strA LaTeX string displaying all intermediate matrices and operations.
"swaps"intThe number of row swaps performed.
"exp"strA LaTeX string for the unsimplified determinant expression (product of sign, scaling factors, and diagonal coefficients), or
"0"if a zero pivot was encountered.
"sc_fact"listThe list of scaling factors extracted from pivot rows (as their inverses, i.e. the actual pivot values before scaling).
"val"strA LaTeX string for the fully evaluated determinant value, or
"0"if a zero pivot was encountered.
"all"strA complete LaTeX string combining the reduction table and the final determinant computation.
- Return type:
dict
Examples
Full determinant computation with details:
>>> A = Matrix([[0, 1], [3, 4]]) >>> result = pxs_determinant(A) >>> result["swaps"] 1 >>> result["val"] '-3'
Singular matrix (zero pivot encountered):
>>> A = Matrix([[1, 2], [2, 4]]) >>> result = pxs_determinant(A) >>> result["val"] '0' >>> result["exp"] '0'
3x3 matrix with scaling factors:
>>> A = Matrix([[2, 4, 0], [1, 3, 1], [0, 1, 2]]) >>> result = pxs_determinant(A) >>> result["sc_fact"] [2]
- Mes_fctions_d_alg_lineaire_bis.pxs_compute_determinant(A, smart=True, **kwargs)[source]
Compute the determinant of a matrix by cofactor expansion along a strategically chosen row or column, with full LaTeX output.
At each recursive step, the function optionally selects the row or column with the fewest non-zero entries (
smart=True) to minimise the number of non-zero terms in the expansion. The result is a complete LaTeXalign*environment showing all intermediate steps down to 2x2 determinants.- Parameters:
A (Matrix) – A square SymPy matrix.
smart (bool, optional) – If
True(default), at each step the row or column with the fewest non-zero entries is selected for elimination, and either row or column operations are applied accordingly. IfFalse, the first column is always used, with row operations only.**kwargs – Additional keyword arguments forwarded to SymPy’s
latex()function.
- Returns:
A LaTeX string showing the full step-by-step determinant computation, from the original matrix down to the final scalar value.
- Return type:
str
Examples
3x3 matrix with smart expansion:
>>> A = Matrix([[1, 0, 0], [2, 3, 1], [0, 4, 2]]) >>> print(pxs_compute_determinant(A)) # LaTeX output exploiting the zeros in the first row
3x3 matrix without smart expansion:
>>> A = Matrix([[2, 1, 3], [0, 4, 1], [1, 2, 0]]) >>> print(pxs_compute_determinant(A, smart=False)) # LaTeX output always expanding along the first column
- Mes_fctions_d_alg_lineaire_bis.pxs_best_line(A)[source]
Identify the row or column of a matrix with the fewest non-zero entries.
This is used to select the most efficient line for cofactor expansion. In case of a tie between the best row and the best column, the column is preferred.
- Parameters:
A (Matrix) – A square SymPy matrix.
- Returns:
rc (str) –
"r"if the best line is a row,"c"if it is a column.k (int) – The 1-based index of that row or column.
Examples
A matrix whose first row has the fewest non-zero entries:
>>> from sympy import Matrix >>> A = Matrix([[1, 0, 0], ... [2, 3, 1], ... [0, 4, 2]]) >>> pxs_best_line(A) ('r', 1)
A matrix whose second column has the fewest non-zero entries:
>>> A = Matrix([[1, 0, 3], ... [2, 0, 1], ... [0, 5, 2]]) >>> pxs_best_line(A) ('c', 2)
Tie between a row and a column — the column is preferred:
>>> A = Matrix([[1, 0, 3], ... [0, 2, 1], ... [4, 5, 6]]) >>> pxs_best_line(A) ('c', 1)
- Mes_fctions_d_alg_lineaire_bis.pxs_expand_determinant(A, rc='s', k=1, color='red', rc_min=None, k_min=None, **kwargs)[source]
Perform one step of cofactor expansion of a determinant along a chosen row or column, and return the resulting LaTeX expression and sub-problems.
The expansion row or column can be specified explicitly, or selected automatically as the one with the fewest non-zero entries. The resulting minors can optionally have one of their own rows or columns highlighted in colour, indicating the line that will be used at the next expansion step.
- Parameters:
A (Matrix) – A square SymPy matrix.
rc (str, optional) –
"r"to expand along a row,"c"to expand along a column, or"s"(default) to select automatically the best line.k (int, optional) – 1-based index of the row or column to expand along. Used only when
rcis"r"or"c". Defaults to1.color (str, optional) – Color name to highlight the selected line inside each minor matrix. Defaults to
"red". PassNoneor""to disable highlighting.rc_min (str or None, optional) –
"r"or"c", pre-specified choice of expansion direction for the minors. IfNone(default), the best line is selected automatically for each minor.k_min (int or None, optional) – 1-based index of the row or column to highlight inside each minor. If
None(default), it is determined automatically.**kwargs – Additional keyword arguments forwarded to SymPy’s
latex()function.
- Returns:
A dictionary with the following keys:
"factors"list of ExprThe signed cofactor scalars
(-1)^(i+j) * a_{ij}for each non-zero entry in the expansion line.
"minors"list of MatrixThe corresponding
(n-1) x (n-1)minor matrices.
"expr"strA LaTeX string of the full cofactor expansion (sum of factors times determinants of minors).
"rc"strThe direction actually used for expansion (
"r"or"c").
"index"intThe 1-based index of the row or column actually used.
- Return type:
dict
Examples
Automatic selection of the best line:
>>> from sympy import Matrix >>> A = Matrix([[1, 0, 0], ... [2, 3, 4], ... [5, 6, 7]]) >>> result = pxs_expand_determinant(A) >>> result["rc"], result["index"] ('r', 1) >>> result["factors"] [1]
Explicit expansion along the second column:
>>> A = Matrix([[1, 2, 3], ... [0, 4, 0], ... [5, 6, 7]]) >>> result = pxs_expand_determinant(A, rc="c", k=2) >>> result["rc"], result["index"] ('c', 2)
Disabling minor highlighting:
>>> result = pxs_expand_determinant(A, color=None) >>> result["expr"] # LaTeX string, no color commands
- Mes_fctions_d_alg_lineaire_bis.pxs_det_full_expand(A, nb_rep=None, rc='s', k=1, name='A', color='red', end=True, **kwargs)[source]
Produce a complete step-by-step cofactor expansion of a determinant, down to 2x2 determinants, as a LaTeX block.
Starting from the full matrix, the function repeatedly applies
pxs_expand_determinantto each minor, building a sequence of aligned LaTeX lines that shows the full expansion tree flattened into a single chain of equalities. At each level, a highlighted row or column inside the minor matrices indicates where the next expansion will be performed.- Parameters:
A (Matrix) – A square SymPy matrix.
nb_rep (int or None, optional) – Number of expansion steps to perform. Must be at most
n - 2wherenis the matrix size. Defaults toNone, meaning all steps are performed down to 2x2 minors.rc (str, optional) –
"r"to always expand along a row,"c"along a column, or"s"(default) to select automatically at each step.k (int, optional) – 1-based index of the row or column to use when
rcis"r"or"c". Defaults to1.name (str, bool, or None, optional) –
Controls how the left-hand side of the first equality is displayed.
A string (e.g.
"A") : displayed as\det A.True: the explicit matrix is rendered, with the expansion line highlighted.FalseorNone: no left-hand side is prepended.
Defaults to
"A".color (str, optional) – Color used to highlight the expansion row or column inside minor matrices. Defaults to
"red". PassNoneto disable.end (bool, optional) – If
True(default), the expansion is completed all the way to the final numerical value. IfFalse, the last step stops at the 2x2 determinant expressions without evaluating them.**kwargs – Additional keyword arguments forwarded to SymPy’s
latex()function.
- Returns:
all_details (str) – A LaTeX string (without the surrounding
equation*environment) showing the full expansion chain.list_lines (list of str) – The individual LaTeX lines of the expansion, including the left-hand side label if
nameis set.
Examples
Full expansion of a 3x3 matrix:
>>> from sympy import Matrix >>> A = Matrix([[1, 2, 3], ... [0, 4, 5], ... [1, 0, 6]]) >>> details, lines = pxs_det_full_expand(A)
Expanding along the second row explicitly:
>>> details, lines = pxs_det_full_expand(A, rc = "r", k = 2)
Limiting the number of expansion steps to 1:
>>> details, lines = pxs_det_full_expand(A, nb_rep = 1)
Disabling the final numerical evaluation:
>>> details, lines = pxs_det_full_expand(A, end = False)
- Mes_fctions_d_alg_lineaire_bis.pxs_full_expand(A, nb_rep=None, rc='s', k=1, name='A', color='red', end=True, **kwargs)
Produce a complete step-by-step cofactor expansion of a determinant, down to 2x2 determinants, as a LaTeX block.
Starting from the full matrix, the function repeatedly applies
pxs_expand_determinantto each minor, building a sequence of aligned LaTeX lines that shows the full expansion tree flattened into a single chain of equalities. At each level, a highlighted row or column inside the minor matrices indicates where the next expansion will be performed.- Parameters:
A (Matrix) – A square SymPy matrix.
nb_rep (int or None, optional) – Number of expansion steps to perform. Must be at most
n - 2wherenis the matrix size. Defaults toNone, meaning all steps are performed down to 2x2 minors.rc (str, optional) –
"r"to always expand along a row,"c"along a column, or"s"(default) to select automatically at each step.k (int, optional) – 1-based index of the row or column to use when
rcis"r"or"c". Defaults to1.name (str, bool, or None, optional) –
Controls how the left-hand side of the first equality is displayed.
A string (e.g.
"A") : displayed as\det A.True: the explicit matrix is rendered, with the expansion line highlighted.FalseorNone: no left-hand side is prepended.
Defaults to
"A".color (str, optional) – Color used to highlight the expansion row or column inside minor matrices. Defaults to
"red". PassNoneto disable.end (bool, optional) – If
True(default), the expansion is completed all the way to the final numerical value. IfFalse, the last step stops at the 2x2 determinant expressions without evaluating them.**kwargs – Additional keyword arguments forwarded to SymPy’s
latex()function.
- Returns:
all_details (str) – A LaTeX string (without the surrounding
equation*environment) showing the full expansion chain.list_lines (list of str) – The individual LaTeX lines of the expansion, including the left-hand side label if
nameis set.
Examples
Full expansion of a 3x3 matrix:
>>> from sympy import Matrix >>> A = Matrix([[1, 2, 3], ... [0, 4, 5], ... [1, 0, 6]]) >>> details, lines = pxs_det_full_expand(A)
Expanding along the second row explicitly:
>>> details, lines = pxs_det_full_expand(A, rc = "r", k = 2)
Limiting the number of expansion steps to 1:
>>> details, lines = pxs_det_full_expand(A, nb_rep = 1)
Disabling the final numerical evaluation:
>>> details, lines = pxs_det_full_expand(A, end = False)
- Mes_fctions_d_alg_lineaire_bis.pxs_char_poly(A, var=' \\lambda ', unit=False, rc='s', k=1, name='A', color='red', **kwargs)[source]
Produce a complete step-by-step cofactor expansion of a characteristic polynomial, down to 2x2 determinants, as a LaTeX block.
Starting from the matrix
A - var*I_n(orvar*I_n - Aifunit=True), the function callspxs_det_full_expandto build a sequence of aligned LaTeX lines showing the full expansion chain. The last line is replaced by the canonical factored form of the characteristic polynomial, computed viapxs_Poly.- Parameters:
A (Matrix) – A square SymPy matrix.
var (str, optional) – LaTeX string for the characteristic variable. Defaults to
r" \lambda ".unit (bool, optional) – If
False(default), the characteristic matrix isA - var*I_n. IfTrue, it isvar*I_n - A.rc (str, optional) –
"r"to always expand along a row,"c"along a column, or"s"(default) to select automatically at each step.k (int, optional) – 1-based index of the row or column to use when
rcis"r"or"c". Defaults to1.name (str, bool, or None, optional) –
Controls how the left-hand side of the first equality is displayed.
A string (e.g.
"A"): displayed as\det(A - \lambda I_n)or\det(\lambda I_n - A)depending onunit.True: the explicit characteristic matrix is rendered, with the expansion line highlighted.FalseorNone: no left-hand side is prepended.
Defaults to
"A".color (str, optional) – Color used to highlight the expansion row or column inside minor matrices. Defaults to
"red". PassNoneto disable.**kwargs – Additional keyword arguments forwarded to SymPy’s
latex()function.
- Returns:
all_details (str) – A LaTeX string (without the surrounding
equation*environment) showing the full expansion chain, ending with the canonical form of the characteristic polynomial.cpoly (Poly) – The characteristic polynomial as a
pxs_Polyobject.
Examples
Full expansion of the characteristic polynomial of a 3x3 matrix:
>>> from sympy import Matrix >>> A = Matrix([[1, 2, 3], ... [0, 4, 5], ... [1, 0, 6]]) >>> details, cpoly = pxs_char_poly(A)
Using the convention
var*I_n - Ainstead:>>> details, cpoly = pxs_char_poly(A, unit=True)
Expanding along the second row with a custom variable name:
>>> details, cpoly = pxs_char_poly(A, var=r" \mu ", rc="r", k=2)
Disabling color highlighting:
>>> details, cpoly = pxs_char_poly(A, color=None)
- Mes_fctions_d_alg_lineaire_bis.pxs_randmatrixrect(p, q, a, b)[source]
Returns a rectangular matrix with p rows and q columns such that every coefficient is a realization of of a discrete random variable on range(a, b)
- returns:
LaTeX bmatrix as a string
- Mes_fctions_d_alg_lineaire_bis.pxs_cptrzeros(M)[source]
En: Counts the number of zero entries in the given matrix M. cpte le nombre de coefficients nuls dans une matrice donnée
- Mes_fctions_d_alg_lineaire_bis.pxs_matelement(p, q, i, j)[source]
En: Renvoie la matrice élémentaire de p lignes et q colonnes avec un 1 à la place i,j. Returns the elementary matrix with p rows and q columns with a 1 at position (i, j). Fr: Renvoie la matrice élémentaire de p lignes et q colonnes avec un 1 à la place i,j.
- Mes_fctions_d_alg_lineaire_bis.pxs_randmatrixInv(p, a, b, r)[source]
- En: Returns an invertible square matrix of size p, with r percent of non-zero entries
(thus [r.p]+1 non-zero elements), and all entries are between a and b-1.
Retourne une matrice carrée de taille p, inversible et dont le nbre de coefficients non nuls est de r pourcent (donc en fait [r.p]+1 éléments non nuls) et dont tous les coefficients sont compris entre a et b-1
Mes_fctions_d_alg_lineaire
- Mes_fctions_d_alg_lineaire.getrandbits(k) x. Generates an int with k random bits.
- Mes_fctions_d_alg_lineaire.diag_tst(res_eigenvects)[source]
En: Checks if for each eigenvalue the multiplicity equals the dimension of the associated eigenspace. Fr: Vérifie si pour chaque valeur propre la multiplicité égale à la dimension du sous espace propre associé
- Mes_fctions_d_alg_lineaire.diag_sympy(M)[source]
En: Tests if a matrix is diagionalizable by checking if for each eigenvalue the multiplicity equals the dimension of the associated eigenspace. If M is s-diagonalizable returns (D,P), which is as a list.; i.e. D = diag_sympy(M)[0] and P = diag_sympy(M)[1]. Fr: Teste si M est diagonalisable. Si c’est le cas, renvoie la matrice diagonale D ainsi que la matrice de passage P présentée sous la forme d’une liste de D = diag_sympy(M)[0] et P = diag_sympy(M)[1].
- Mes_fctions_d_alg_lineaire.puissance_exact(M, p)[source]
En: Reurns the p^th power of Matrix M. i.e. M^p. Fr: .
- Mes_fctions_d_alg_lineaire.mat_element(p, q, i, j)[source]
En: Renvoie la matrice élémentaire de p lignes et q colonnes avec un 1 à la place i,j. Returns the elementary matrix with p rows and q columns with a 1 at position (i, j). Fr: Renvoie la matrice élémentaire de p lignes et q colonnes avec un 1 à la place i,j.
- Mes_fctions_d_alg_lineaire.Cptrzeros(M)[source]
En: Counts the number of zero entries in the given matrix M. cpte le nombre de coefficients nuls dans une matrice donnée
- Mes_fctions_d_alg_lineaire.randmatrixrect(p, q, a, b)[source]
Returns a rectangular matrix with p rows and q columns such that every coefficient is a realization of of a discrete random variable on range(a, b)
- returns:
LaTeX bmatrix as a string
- Mes_fctions_d_alg_lineaire.randmatrix(p, a, b)[source]
Returns a square matrix of size p such that every coefficient is a realization of of a uniform discrete random variable within the range(a,b)
- Mes_fctions_d_alg_lineaire.randmatrixdiagonale(p, a, b)[source]
Returns a square diagonal matrix of size p such that every coefficient is a realization of a uniform discrete random variable, the range of which is range(a, b)
- Mes_fctions_d_alg_lineaire.randmatrixdiagonalesorted(p, a, b)[source]
Returns a square diagonal matrix, denoted D, of size p, such that every coefficient is a realization of a uniform discrete random variable in range(a, b). Moreover, the eigen values of D are sorted in the increasing order
- Mes_fctions_d_alg_lineaire.randmatrixdiagonaleinversible(p, a, b)[source]
Returns a square invertible diagonal matrix of size p such that every coefficient is a realization of a uniform discrete random variable in the range (a, b).
- Mes_fctions_d_alg_lineaire.randmatrixInvnew(p, a, b, r)[source]
- En: Returns an invertible square matrix of size p, with r percent of non-zero entries
(thus [r.p]+1 non-zero elements), and all entries are between a and b-1.
Retourne une matrice carrée de taille p, inversible et dont le nbre de coefficients non nuls est de r pourcent (donc en fait [r.p]+1 éléments non nuls) et dont tous les coefficients sont compris entre a et b-1
- Mes_fctions_d_alg_lineaire.randmatrixInvnewparpaquet(n, p, a, b, r)[source]
Returns a list of n invertible square matrices of size p, with r percent of non-zero entries (rounded up if the decimal is >= 0.5 and down otherwise). Additionally, all entries are between a and b-1, and the positions of zero entries are chosen randomly among all possible positions.
Retourne une liste de n matrices carrées de taille p, inversible, et dont le nbre de coefficients non nuls est de r pourcent (arrondi à la décimale supérieure si elle >=0.5 et infériure sinon. De plus tous les coefficients sont compris entre a et b-1. Enfin l’emplacement de chaque coef nul est choisi aléatoirement parmi tous les emplacements de coefficients.
- Mes_fctions_d_alg_lineaire.selectRandom(names)[source]
Sélectionne au hasard un élément dans une liste
- Mes_fctions_d_alg_lineaire.randmatrixInvnewzerosaleatoire(p, a, b, r)[source]
Returns an invertible square matrix of size p, with r/100 non-zero entries (rounded up if the decimal is >= 0.5 and down otherwise). Additionally, all entries are between a and b-1, and the positions of zero entries are chosen randomly among all possible positions.
Retourne une matrice carrée de taille p, inversible, et dont le nbre de coefficients non nuls est de r/100 (arrondi à la décimale supérieure si elle >=0.5 et inférieure sinon. De plus tous les coefficients sont compris entre a et b-1. Enfin l’emplacement de chaque coef nul est choisi aléatoirement parmi tous les emplacements de coefficients.
- Mes_fctions_d_alg_lineaire.randdiagomatrixeigvaluesorted(p, a, b, aprime, bprime, pourcent)[source]
Returns a square diagonalizable matrix of size p, the coefficients of which are randomly chosen. More precisely, we start from a diagonal matrix D (with increasing eigen values, all between a and b). Then we define M = P^-1 D P, where P is an invertible matrix (obtained by using P = randmatrixInvnewzerosaleatoire(p,aprime,bprime, pourcent, exprimé en 45 si c’est 45% d’entrées non nulles dans P) ) returns M
- Mes_fctions_d_alg_lineaire.randmatrixInvnewzerosaleatoireparpaquet(n, p, a, b, r)[source]
Returns a list of n invertible square matrices of size p, with r/100 non-zero entries (rounded up if the decimal is >= 0.5 and down otherwise). Additionally, all entries are between a and b-1, and the positions of zero entries are chosen randomly among all possible positions.
Retourne une liste de n matrices carrées de taille p, inversible, et dont le nbre de coefficients non nuls est de r/100 (arrondi à la décimale supérieure si elle >=0.5 et infériure sinon. De plus tous les coefficients sont compris entre a et b-1. Enfin l’emplacement de chaque coef nul est choisi aléatoirement parmi tous les emplacements de coefficients.
- Mes_fctions_d_alg_lineaire.EcritureLatexdesmatricesinversiblesainversergroupeespar3(n, p, a, b, r)[source]
Returns the matrices to be inverted, created by calling randmatrixInvnewparpaquet(3,4,-9,10,100), grouped m by m, and written in TeX format. randmatrixInvnewparpaquet(n,p,a,b,r): Retourne les matrices à invreser, créées par appel de randmatrixInvnewparpaquet(3,4,-9,10,100), groupées m par m, et écrites en Tex randmatrixInvnewparpaquet(n,p,a,b,r):
- Mes_fctions_d_alg_lineaire.Ecriture(A, n, p, a, b, r)[source]
Returns the matrices to be inverted, created by calling randmatrixInvnewparpaquet(3,4,-9,10,100), grouped m by m, and written in TeX format. randmatrixInvnewparpaquet(n,p,a,b,r):
Retourne les matrices à inverser, créées par appel de randmatrixInvnewparpaquet(3,4,-9,10,100), groupées m par m, et écrites en Tex randmatrixInvnewparpaquet(n,p,a,b,r):
- Mes_fctions_d_alg_lineaire.Ecritureavecinverse(A, n, p, a, b, r)[source]
- Returns the matrices to be inverted, created by calling randmatrixInvnewparpaquet(3,4,-9,10,100),
grouped m by m, and written in TeX format. randmatrixInvnewparpaquet(n,p,a,b,r):
Retourne les matrices à invreser, créées par appel de randmatrixInvnewparpaquet(3,4,-9,10,100), groupées m par m, et écrites en Tex randmatrixInvnewparpaquet(n,p,a,b,r):
- Mes_fctions_d_alg_lineaire.trafiquematrice(M)[source]
En: For any matrix A, returns the matrix A with exactly one element modified. The modified element, which is a non-zero element is arbitrarily chosen and mulitplied a random number between -5 and 5, 0 being exluded. In other word, a_i,j becomes k a_ij, for an non zero element a_i,j Fr:
- Mes_fctions_d_alg_lineaire.trafiquematricerestantinversible(M)[source]
Pour toute matrice inversible A, retourne la matrice A, à un élément près, de telle sorte que la matrice trafiquée reste inversible.
- Mes_fctions_d_alg_lineaire.standard_basis_vector(n, p)[source]
Retourne le vecteur e_p de R^n, i.e. (0,0,….,0,1,0,…,0)
- Mes_fctions_d_alg_lineaire.Polynomial_of_Matrix(P, A)[source]
Renvoie la matrice P(A), où P est un polynôme
- Mes_fctions_d_alg_lineaire.Polynomial_of_Matrix_extended_v_5(P, name_polynomial, A, name_matrix)[source]
Renvoie la matrice P(A), où P est un polynôme avec les 4 étapes de calculs dans une liste. Chaque étape étant un élément de la liste de résulat. Le dernier élement de la liste de résultat n’est autre que le TeX dans un alignetoile de toute la séquence
- Mes_fctions_d_alg_lineaire.Polynomial_of_Matrix_extended_v7(P, A, name_matrix)[source]
Renvoie la matrice P(A), où P est un polynôme avec les 4 étapes de calculs dans une liste
Mes_fctions_d_analyse_bis
Created on Thu Mar 17 19:11:52 2022
@author: jlebovits
- Mes_fctions_d_analyse_bis.pxsl_par(expr, minus=False, add=False)[source]
Wraps a LaTeX expression in parentheses if it starts with a minus sign or if ti is an Add.
- Parameters:
expr (sympy expression or numeric) – The expression to be displayed.
- Returns:
myst – The LaTeX string, wrapped in parentheses if negative or Add.
- Return type:
LaTeX-formatted object (via the myst function)
- Mes_fctions_d_analyse_bis.pxs_explain_IBP(var=x, f1=None, f2=None, type_int='udv', a=None, b=None, nb_IBP=1, intro=True, conclude=True, link='https://app.pyxiscience.com/teacher/modules/7e0b271d-92f9-11f0-a777-0e37881c19a9/chapter/258e5825-9de5-11f0-a5a8-0e37881c19a9#quotient-fini#IBP2')[source]
Creates a complete bilingual LaTeX explanation for computing an integral using the Integration by Parts (IBP) method.
This is the main public-facing function that introduces the IBP concept, calls the internal recursive explanation generator _pxs_explain_IBP, and concludes by showing the final boxed result of the integral (definite or indefinite).
- Parameters:
var (sympy Symbol) – The integration variable.
f1 (sympy expressions) – The two parts of the integrand (used as u and dv or du and v).
f2 (sympy expressions) – The two parts of the integrand (used as u and dv or du and v).
type_int (str, optional) – Type of integration by parts (“udv” or “vdu”). Default is “udv”.
a (numeric or symbolic, optional) – Lower and upper bounds of the integral. If None, it’s treated as an indefinite integral.
b (numeric or symbolic, optional) – Lower and upper bounds of the integral. If None, it’s treated as an indefinite integral.
nb_IBP (int, optional) – Number of integrations by parts to perform (1 or 2). Default is 1.
- Returns:
A bilingual LaTeX-formatted text containing the full reasoning, step-by-step explanation, and final boxed conclusion of the IBP process.
- Return type:
str
- Mes_fctions_d_analyse_bis.pxsl_partial_decomp(num: list = [], den: list = [], var=x, mul_symbol=src.scripts.pxs_runtime.myst, method='simple') dict[source]
Construct the symbolic structure of a partial fraction decomposition.
The function analyzes the denominator factors, generates the appropriate elementary fractions (including powers for repeated factors), assigns symbolic coefficients (A, B, C, …), and builds the associated identity equation.
- Parameters:
num (list, optional) – List representing the numerator (kept for consistency, not expanded here).
den (list, optional) – List of denominator factors (SymPy expressions).
var (Symbol, optional) – Main symbolic variable (default is
Symbol('x')).mul_symbol (Any, optional) – Multiplication symbol used in LaTeX rendering.
method (str, optional) – Decomposition method: “simple” or “advanced” (default is “simple”). If “simple”, one letter by term, if “advanced”, linear terms for irreducible quadratics.
- Returns:
A dictionary containing: - num : list - den : list - letters : list of str - elem_list : list of denominator elements - var : Symbol - expr : symbolic sum of elementary fractions - identity : simplified identity after clearing denominators
- Return type:
dict
Examples
Basic usage (distinct linear factors) >>> from sympy import Symbol >>> x = Symbol(‘x’) >>> sol = pxsl_partial_decomp(den=[x, x - 1]) >>> sol[“letters”] [‘A’, ‘B’] >>> sol[“expr”] A/x + B/(x - 1)
Repeated factor (powers are generated automatically) >>> sol = pxsl_partial_decomp(den=[x, (x - 1)**2]) >>> sol[“letters”] [‘A’, ‘B’, ‘C’] >>> sol[“expr”] A/x + B/(x - 1) + C/(x - 1)**2
Mix of repeated and distinct factors >>> sol = pxsl_partial_decomp(den=[(x + 2)**3, (2*x - 1)]) >>> sol[“letters”] [‘A’, ‘B’, ‘C’, ‘D’] >>> sol[“expr”] A/(x + 2) + B/(x + 2)**2 + C/(x + 2)**3 + D/(2*x - 1)
Advanced mode (irreducible quadratic gets a linear numerator) >>> sol = pxsl_partial_decomp(den=[x**2 + 1], method=”advanced”) >>> sol[“letters”] [‘A’, ‘B’] >>> sol[“expr”] (A*x + B)/(x**2 + 1)
Advanced mode with a mix (quadratic + repeated linear factor) >>> sol = pxsl_partial_decomp(den=[x**2 + 1, (x - 3)**2], method=”advanced”) >>> sol[“letters”] [‘A’, ‘B’, ‘C’, ‘D’] >>> sol[“expr”] (A*x + B)/(x**2 + 1) + C/(x - 3) + D/(x - 3)**2
Identity after clearing denominators (useful to solve for coefficients) >>> sol = pxsl_partial_decomp(den=[x, x - 1]) >>> sol[“identity”] A*(x - 1) + B*x
- Mes_fctions_d_analyse_bis.pxsl_decomp_sol(sol: dict, x_0, mul_symbol: str = '', par: bool = False) None[source]
Generate and store the LaTeX representation of the decomposition identity evaluated at a specific value of the variable.
The result is stored directly in the solution dictionary under a dynamically generated key.
- Parameters:
sol (dict) – Dictionary produced by
pxsl_partial_decomp.x_0 (int or float) – Value substituted for the main variable.
mul_symbol (str, optional) – Multiplication symbol used in LaTeX output.
par (bool, optional) – If True, negative values of x_0 are enclosed in parentheses.
- Returns:
The dictionary is modified in place by adding a LaTeX string.
- Return type:
None
Examples
>>> pxsl_decomp_sol(sol, 2) >>> "expr_2" in sol True
Mes_fctions_d_analyse
Created on Thu Mar 17 19:11:52 2022
@author: jlebovits
- Mes_fctions_d_analyse.pxsl_par_minus(expr)[source]
Wraps a LaTeX expression in parentheses if it starts with a minus sign.
- Parameters:
expr (sympy expression or numeric) – The expression to be displayed.
- Returns:
myst – The LaTeX string, wrapped in parentheses if negative.
- Return type:
LaTeX-formatted object (via the myst function)
- Mes_fctions_d_analyse.pxsl_par(expr)[source]
Wraps a LaTeX expression in parentheses if it starts with a minus sign or if ti is an Add.
- Parameters:
expr (sympy expression or numeric) – The expression to be displayed.
- Returns:
myst – The LaTeX string, wrapped in parentheses if negative or Add.
- Return type:
LaTeX-formatted object (via the myst function)
- Mes_fctions_d_analyse.pxsl_par_add(expr)[source]
Wraps a LaTeX expression in parentheses if it is an Add object.
- Parameters:
expr (sympy expression or numeric) – The expression to be displayed.
- Returns:
myst – The LaTeX string, wrapped in parentheses if Add.
- Return type:
LaTeX-formatted object (via the myst function)
- Mes_fctions_d_analyse.pxs_explain_IBP(var=x, f1=None, f2=None, type_int='udv', a=None, b=None, nb_IBP=1, link='https://app.pyxiscience.com/teacher/modules/7e0b271d-92f9-11f0-a777-0e37881c19a9/chapter/258e5825-9de5-11f0-a5a8-0e37881c19a9#quotient-fini#IBP2')[source]
Creates a complete bilingual LaTeX explanation for computing an integral using the Integration by Parts (IBP) method.
This is the main public-facing function that introduces the IBP concept, calls the internal recursive explanation generator _pxs_explain_IBP, and concludes by showing the final boxed result of the integral (definite or indefinite).
- Parameters:
var (sympy Symbol) – The integration variable.
f1 (sympy expressions) – The two parts of the integrand (used as u and dv or du and v).
f2 (sympy expressions) – The two parts of the integrand (used as u and dv or du and v).
type_int (str, optional) – Type of integration by parts (“udv” or “vdu”). Default is “udv”.
a (numeric or symbolic, optional) – Lower and upper bounds of the integral. If None, it’s treated as an indefinite integral.
b (numeric or symbolic, optional) – Lower and upper bounds of the integral. If None, it’s treated as an indefinite integral.
nb_IBP (int, optional) – Number of integrations by parts to perform (1 or 2). Default is 1.
- Returns:
A bilingual LaTeX-formatted text containing the full reasoning, step-by-step explanation, and final boxed conclusion of the IBP process.
- Return type:
str
Mes_fctions_d_ecriture_Latex
Created on Thu Mar 17 19:11:52 2022
@author: jlebovits
- Mes_fctions_d_ecriture_Latex.EcrituredsAlignetoileLatex_one_per_line(L_nom, L)[source]
Retourne en TeX, dans un align, les éléments de la liste L, avec, comme noms les éléments de la liste L_nom, sous le format, L_nom[i] &= L[i] , pour chaque ligne )
- Mes_fctions_d_ecriture_Latex.EcrituredsAlignetoileLatex_bis(L_nom, L, q)[source]
Retourne en TeX, dans un align*, les éléments de la liste L, avec, comme noms les éléments de la liste L_nom, sous le format, L_nom[i]= L[i], regroupés par paquet de q à chaque ligne (où q est un entier)
- Mes_fctions_d_ecriture_Latex.EcrituredsAlignetoileLatex(L_nom, L, q)[source]
Retourne en TeX, dans un align, les éléments de la liste L, avec, comme noms les éléments de la liste L_nom, sous le format, L_nom[i]= L[i], regroupés par paquet de q à chaque ligne (où q est un entier)
- Mes_fctions_d_ecriture_Latex.EcrituredsAlignLatex(L_nom, L, q, labellatex)[source]
Retourne en TeX, dans un align, les éléments de la liste L, avec, comme noms les éléments de la liste L_nom, sous le format, L_nom[i]= L[i], regroupés par paquet de q à chaque ligne (où q est un entier)
- Mes_fctions_d_ecriture_Latex.Essaiprint(var)[source]
permet d’écrire des variables dans des equations Latex et tout et tout et tout
- Mes_fctions_d_ecriture_Latex.Content(L)[source]
Donne le contenu de toute la liste L, en en séparant les élements par des virgules (en particulier plus de crochets)
- Mes_fctions_d_ecriture_Latex.absprpolynomebis(var, Z)[source]
Fonction qui rendra X-r, r étant un réel, bien écrit en TeX (si on utilise EssaiPrint) et qui gère les cas (X–0), (X–2), (X-+2),….
- Mes_fctions_d_ecriture_Latex.Content_pr_python_latex(L)[source]
Renvoie, sous forme de string, le contenu de toute la liste L, en en séparant les éléments par des virgules (en particulier plus de crochets)
- Mes_fctions_d_ecriture_Latex.Content_pr_python_latex_avec_sep(L, sep)[source]
Renvoie, sous forme de string, le contenu de toute la liste L, en en séparant les éléments par des virgules (en particulier plus de crochets)
- Mes_fctions_d_ecriture_Latex.Content_ss_virg(L)[source]
Donne le contenu de toute la liste L, en en séparant les éléments par des virgules (en particulier plus de crochets)
- Mes_fctions_d_ecriture_Latex.Content_ss_virg_ss_print(L)[source]
renvoie phrase qui est le contenu de toute la liste L, sans l’imprimer’, en en séparant les éléments par des virgules (en particulier plus de crochets)
- Mes_fctions_d_ecriture_Latex.Content_avec_sep_de_mon_choix(L, sepa)[source]
Imprime le contenu de toute la liste L, en en séparant les éléments par des sepa, où sepa est une chaine de caractères
- Mes_fctions_d_ecriture_Latex.Latex_Roots_Poly_char(CopySteps, CopyStepsbis, CopyStepster)[source]
Retourne, au format latex toutes le calcul du polynôme carcatéristique et de toutes les dérivées successives interessantes en les racines données dans l’enoncé
- Mes_fctions_d_ecriture_Latex.standard_basis_vector(n, p)[source]
“Retourne le vecteur e_p de R^n, i.e. (0,0,….,0,1,0,…,0) où le 1 est en p-ième position sous forme de matrix sympy: Attention avec le décalage de python la 1ere ligne est la ligne 0
- Mes_fctions_d_ecriture_Latex.Eigen_Spaces_ds_align_latex(M, E, etat, nbre_de_paquets, labellatex)[source]
Retourne dans un align, par paquet de nbre_de_paquets termes, les sous-espaces propres de M,
- Mes_fctions_d_ecriture_Latex.Dim_Eigen_Spaces_ds_align_latex(M, E, etat, nbre_de_paquets, labellatex)[source]
Retourne dans un align, par paquet de q termes, la dimension des sous-espaces propres de M,
- Mes_fctions_d_ecriture_Latex.Eigen_Vectors_ds_align_latex(M, f, etat, nbre_de_paquets, labellatex)[source]
Retourne dans un align, par paquet de nbre_de_paquets termes, les vecteurs propres de M,
- Mes_fctions_d_ecriture_Latex.Liste_de_ts_les_vec_propres(M)[source]
Retourne dans une liste, tous les vecteurs propres de M, comme ils apparaissent dans EVM
- Mes_fctions_d_ecriture_Latex.Matrice_Pass_Base_canonique_a_base_de_vect_propres(M)[source]
Retourne la matrice de passage de la base canonique de K^n, où n=nbre de lignes de l amatrice carrée M, vers la base de vecteurs propres de M, obtenus en utilisant la fonction Liste_de_ts_les_vec_propres(M)
- Mes_fctions_d_ecriture_Latex.Linear_Map_from_a_Matrix(u, x, M)[source]
Retourne l’application linéaire u:K^p -> K^q, assosciée à la matrice M
- Mes_fctions_d_ecriture_Latex.Vec_seul(x, p)[source]
Retourne le vecteur x:=(x_{1},x_{2},…,x_{p}) verticalement
- Mes_fctions_d_ecriture_Latex.Merge_Lists_Symbol(L_1, L_2, L_3)[source]
Renvoi une unique liste, notée L, sur le modèle suivant L[i] = L_1[i] L_3[i] L_2[i], pour i de 0 à len(L1)-1, ou les trois listes ont la même longueur et ou, si L_3 n’est pas une liste, alors on la créer avec un seul symbole répété len(L1) fois
- Mes_fctions_d_ecriture_Latex.Merge_Lists_in_Align_etoile_Latex(L, symb, symbfinal)[source]
Retourne en TeX, dans un align*, les éléments de chacune des listes contenues dans la liste L, en mettant un élement de chaque par ligne. Ainsi, si L_1, L_2 et L_3 sont trois listes et que L=[L_1, L_2, L_3], alors on renverra # begin{align*} &L_1[0],& &L_2[0],& &L_3[0],& &L_1[1],& &L_2[1],& &L_3[1],&
…
&L_1[len(L_1)-1],& &L_2[len(L_1)-1],& &L_3[len(L_1)-1],& end{align*} #
- Mes_fctions_d_ecriture_Latex.Ecriture_Poly_en_Latex(P, symbol)[source]
- Renvoie une liste de deux éléments: chacun de ces élements donne
le polynôme P, écrit en Tex, avec symbol (qui est une chaine de caractères) comme indéterminée etles monômes sont donnés par ordre:
-croissant dans la première liste -décroissant décroissant dans la deuxième liste
- Mes_fctions_d_ecriture_Latex.Ecriture_Poly_en_Latex_dec(P, symbol)[source]
- Renvoie une liste de deux éléments: chacun de ces élements donne
le polynôme P, écrit en Tex, avec symbol (qui est une chaine de caractères) comme indéterminée etles monômes sont donnés par ordre:
-décroissant décroissant #dans la deuxième liste
- Mes_fctions_d_ecriture_Latex.Ecriture_Poly_en_Latex_inc(P, symbol)[source]
- Renvoie une liste de deux éléments: chacun de ces élements donne
le polynôme P, écrit en Tex, avec symbol (qui est une chaine de caractères) comme indéterminée etles monômes sont donnés par ordre:
-croissant
- Mes_fctions_d_ecriture_Latex.Ecriture_Poly_en_Latex_v2(P, symbol)[source]
- Renvoie une liste de deux éléments: chacun de ces élements donne
le polynôme P, écrit en Tex, avec symbol (qui est une chaine de caractères) comme indéterminée etles monômes sont donnés par ordre:
-décroissant décroissant dans la deuxième liste -croissant dans la première liste
- Mes_fctions_d_ecriture_Latex.Ecriture_Poly_of_Matrix_en_Latex(P, Name_Matrix, Size_Matrix)[source]
- Renvoie une liste de deux éléments: chacun de ces élements donne
le polynôme P(Name_Matrix), écrit en Tex, et dont les monômes sont donnés par ordre:
-croissant dans la première liste -décroissant décroissant dans la deuxième liste
- Mes_fctions_d_ecriture_Latex.Ecriture_Poly_of_Matrix_en_Latex_dec(P, Name_Matrix, Size_Matrix)[source]
Renvoie le polynôme P(‘Name_Matrix’), écrit en Tex, et dont les monômes sont donnés par ordre décroissant -P est un polynôme -Name_Matrix est une chaine de caractères (nom de la matrice carée dont il est question) -Size_Matrix est la taille de la matrice carrée nommée Name_Matrix
- Mes_fctions_d_ecriture_Latex.Ecriture_Poly_of_Matrix_en_Latex_inc(P, Name_Matrix, Size_Matrix)[source]
Renvoie le polynôme P(‘Name_Matrix’), écrit en Tex, et dont les monômes sont donnés par ordre croissant -P est un polynôme -Name_Matrix est une chaine de caractères (nom de la matrice carée dont il est question) -Size_Matrix est la taille de la matrice carrée nommée Name_Matrix
Mes_fctions_deterministes
Created on Thu Mar 17 19:11:52 2022 @author: jlebovits
- Mes_fctions_deterministes.Namings(name, *args)[source]
Fction permettant de créer une fonction dont le nom est donné en argument
- Mes_fctions_deterministes.indfction(a, b, x)[source]
Pour tout a,b et x donnés renvoie la valeur de la fction indicatrice i1_{[a,b]}(x)
- Mes_fctions_deterministes.Indicatfction(a, b)[source]
Pour tout a et b donnés, renvoie la fction x|–> i1_{[a,b]}(x)
- Mes_fctions_deterministes.indfction_v_2(l, a, b, r, x)[source]
Pour tout (a,b,x) donnés renvoie la valeur i1_{a,b}(x) , où la nature des bornes (ouvertes ou fermées) doivent être précisées
- Mes_fctions_deterministes.indi_l_r(l, a, b, r)[source]
Pour tout a et b donnés, renvoie la fction x|–> i1_{a,b}(x), où la nature des bornes (ouvertes ou fermées) doivent être précisées
- Mes_fctions_deterministes.h_l_r(l, a, b, r)[source]
Pour tout a et b donnés, renvoie la fction x|–> x.i1_{a,b}(x), où la nature des bornes (ouvertes ou fermées) doivent être précisées
- Mes_fctions_deterministes.indi_l_r_symb(l, alpha, beta, r)[source]
Pour tout (alpha,beta,x) donnés renvoie la fction x|–> i1_{a,b}(x) , où la nature des bornes, notées ici l et r, (ouvertes ou fermées) doivent être précisées
- Mes_fctions_deterministes.indfction_v_1(l, a, b, r, t)[source]
Pour tout (a,b,t) donnés renvoie la valeur i1_{a,b}(t) , où la nature des bornes (ouvertes ou fermées) doivent être précisées
Mes_fctions_generales
- Mes_fctions_generales.pxs_round(x, ndigits=0)[source]
Fr : Description en français En : pxs_round() function works like the high school students’ calculators. It is analogous to the python round() function, except that Round() don’t use the round to even convention. For example: Round(0.125, 2) = 0.13 while round(0.125, 2) = 0.12
Round a number x to a given precision in decimal digits. The return value is an integer if ndigits is omitted or None or 0 or negative. Otherwise the return value is a floating point number.
Version 1 :
Vérification
Auteur : Jean-Luc Durand Vérificateurs : Joachim, Delphine, Ronan
Paramètres
x : float (to be rounded)
- ndigitsint positive, null or negative
Valeur (numérique ou symbolique) de la puissance, 1 par défaut
Retour
- float
retourne l’arrondi sous forme de float
Fonction utilisée par
d????? à préciser
Mes_fctions_generalistes_bis
Mes_fctions_generalistes_bis - Gestion de certaines fonctions de formatage Latex. Pour voir les tests unitaires s’afficher dans l’éditeur ———————————————————————- >>> begin{python} >>> # Code Python : Ecrivez ci-dessous votre code Python >>> from src.scripts.tests.test_Mes_fctions_generalistes_bis import print_tests_Mes_fctions_generalistes_bis >>> print_tests_Mes_fctions_generalistes_bis() >>> end{python}
- class Mes_fctions_generalistes_bis.pxs_Interval(start, end, left_open=False, right_open=False)[source]
Classe personnalisée héritant de Interval de SymPy Permet un affichage formaté des intervalles avec : - Séparateurs de milliers pour les grands nombres - Notation française pour l’infini et les intervalles
- print(res_num=False, dec=4)[source]
Méthode pour générer une représentation LaTeX formatée de l’intervalle
- Returns:
Chaîne LaTeX formatée selon les conventions françaises
- Return type:
str
- default_assumptions = {}
- Mes_fctions_generalistes_bis.pxs_config(mul_symbol: str = '') dict[source]
Build a configuration dictionary for LaTeX rendering, depending on the current pyxisciences language settings.
The language is retrieved using get_pxs_lang() and affects some formatting options, such as the decimal separator.
- Parameters:
mul_symbol (str, optional) – Multiplication symbol to be used in LaTeX output (default is “”).
- Returns:
A dictionary containing LaTeX configuration options, including: - ln_notation : bool - mul_symbol : str - order : str - decimal_separator : str - inv_trig_style : str
- Return type:
dict
Examples
>>> pxs_config() {'ln_notation': True, 'mul_symbol': '', 'order': 'lex', ...}
- Mes_fctions_generalistes_bis.pxsl_mult(val, mult=src.scripts.pxs_runtime.myst)[source]
Return a multiplication symbol or a blank space depending on the coefficient value.
This function is used to avoid displaying an explicit multiplication symbol when the coefficient is 0, 1, or -1, following standard mathematical conventions.
- Parameters:
val (Any) – Coefficient value to be tested (typically a numeric or SymPy object).
mult (Any, optional) – LaTeX representation (or compatible object) of the multiplication symbol. Default is
myst(r"\cdot").
- Returns:
The multiplication symbol if val is not equal to 0, 1, or -1; otherwise, a blank space.
- Return type:
Any
Examples
>>> pxsl_mult(3) \cdot
>>> pxsl_mult(1)
- Mes_fctions_generalistes_bis.pxsl_symb(val, symb=src.scripts.pxs_runtime.myst, ones=True)[source]
Return a symbol (e.g.
+,-,\cdot) or a blank space depending on the coefficient value and formatting options.This function controls whether an explicit symbol should be displayed in LaTeX output, depending on the value of a coefficient and common mathematical conventions.
By default (
ones=True), the symbol is displayed whenever the coefficient is nonzero (including when it is 1 or -1). Settingones=Falserestores the usual convention where the symbol is omitted for coefficients 0, 1, or -1.- Parameters:
val (Any) – Coefficient value to be tested (typically a numeric or SymPy object).
symb (Any, optional) – LaTeX representation (or compatible object) of the symbol to display (e.g.
myst(r"+"),myst(r"\cdot")). Default ismyst(r"+").ones (bool, optional) – If
True(default), the symbol is displayed whenevervalis nonzero (including whenvalis 1 or -1). IfFalse, the symbol is omitted whenvalis 0, 1, or -1.
- Returns:
The symbol if the conditions are met; otherwise, a blank space (
myst(r" ")).- Return type:
Any
Examples
>>> pxsl_symb(3) +
>>> pxsl_symb(1) +
>>> pxsl_symb(1, ones=False)
>>> pxsl_symb(0)
>>> pxsl_symb(0, ones=True)
- Mes_fctions_generalistes_bis.pxsl_sign(expr: str)[source]
{py:function} Returns the sign of an expression in LaTeX format.
This function takes an expression and returns its sign in LaTeX format: ‘+’ if the expression is positive, ‘-’ if it is negative, and ‘’ (empty string) if it is zero.
- Parameters:
sympy.Expr – The expression whose sign we want to determine.
- Returns:
The sign of the expression in LaTeX format.
- Return type:
str
Examples
>>> pxsl_sign(5) '+'
>>> pxsl_sign(-3) '-'
>>> pxsl_sign(0) ''
- Mes_fctions_generalistes_bis.formater_nombre(nombre)[source]
Formate un nombre en ajoutant des espaces pour les milliers et gère l’infini.
Cette fonction prend un nombre et le formate pour l’affichage LaTeX en ajoutant des espaces pour séparer les milliers. Elle gère également les cas spéciaux de l’infini positif et négatif.
- Parameters:
nombre (int, float, or sympy.core.numbers.Infinity) – Le nombre à formater. Peut être un entier, un flottant, ou l’infini.
- Returns:
Le nombre formaté avec des espaces pour les milliers ou la représentation LaTeX de l’infini.
- Return type:
str
Examples
>>> formater_nombre(1234) '1\ 234'
>>> formater_nombre(1000000) '1\ 000\ 000'
>>> formater_nombre(oo) '\infty'
>>> formater_nombre(-oo) '-\infty'
- Mes_fctions_generalistes_bis.pxsl_formater_nombre(nombre)[source]
Formate un nombre en ajoutant des espaces pour les milliers et gère l’infini.
Cette fonction prend un nombre et le formate pour l’affichage LaTeX en ajoutant des espaces pour séparer les milliers. Elle gère également les cas spéciaux de l’infini positif et négatif.
- Parameters:
nombre (int, float, or sympy.core.numbers.Infinity) – Le nombre à formater. Peut être un entier, un flottant, ou l’infini.
- Returns:
Le nombre formaté avec des espaces pour les milliers ou la représentation LaTeX de l’infini.
- Return type:
str
Examples
>>> pxsl_formater_nombre(1234) '1\ 234'
>>> pxsl_formater_nombre(1000000) '1\ 000\ 000'
>>> pxsl_formater_nombre(oo) '\infty'
>>> pxsl_formater_nombre(-oo) '-\infty'
- Mes_fctions_generalistes_bis.pxsl_format_number(number)[source]
en{Formats a number by adding spaces for thousands and handles infinity.}
r{Formate un nombre en ajoutant des espaces pour les milliers et gère l’infini.}
en{This function takes a number and formats it for LaTeX display by adding spaces to separate thousands. It also handles the special cases of positive and negative infinity.}
- r{Cette fonction prend un nombre et le formate pour l’affichage LaTeX en ajoutant
des espaces pour séparer les milliers. Elle gère également les cas spéciaux de l’infini positif et négatif.}
- numberint, float, or sympy.core.numbers.Infinity
en{The number to format. Can be an integer, a float, or infinity.}
r{Le nombre à formater. Peut être un entier, un flottant, ou l’infini.}
- str
en{The number formatted with spaces for thousands or its LaTeX representation of infinity.}
r{Le nombre formaté avec des espaces pour les milliers ou la représentation LaTeX de l’infini.}
>>> pxsl_format_number(1234) '1\ 234'
>>> pxsl_format_number(1000000) '1\ 000\ 000'
>>> pxsl_format_number(oo) '\infty'
>>> pxsl_format_number(-oo) '-\infty'
- Mes_fctions_generalistes_bis.latex_avec_formatage(expr, sign=False, display=True)[source]
Wrapper LaTeX qui applique le formatage des nombres.
Cette fonction prend une expression et la convertit en format LaTeX en appliquant un formatage spécial pour les grands nombres (>= 1000). Elle gère les entiers, flottants, fractions rationnelles et expressions SymPy.
- Parameters:
expr (int, float, sympy.Rational, or sympy.Expr) – L’expression à convertir en LaTeX avec formatage.
- Returns:
La représentation LaTeX de l’expression avec formatage appliqué.
- Return type:
str
Examples
>>> latex_avec_formatage(1500) '1\ 500'
>>> latex_avec_formatage(Rational(2000, 3)) '\frac{2\ 000}{3}'
>>> latex_avec_formatage(Rational(1, 2)) '\frac{1}{2}'
- Mes_fctions_generalistes_bis.pxsl_latex_avec_formatage(expr, sign=False, display=True)[source]
Wrapper LaTeX qui applique le formatage des nombres.
Cette fonction prend une expression et la convertit en format LaTeX en appliquant un formatage spécial pour les grands nombres (>= 1000). Elle gère les entiers, flottants, fractions rationnelles et expressions SymPy.
- Parameters:
expr (int, float, sympy.Rational, or sympy.Expr) – L’expression à convertir en LaTeX avec formatage.
- Returns:
La représentation LaTeX de l’expression avec formatage appliqué.
- Return type:
str
Examples
>>> pxsl_latex_avec_formatage(1500) '1\ 500'
>>> pxsl_latex_avec_formatage(Rational(2000, 3)) '\frac{2\ 000}{3}'
>>> pxsl_latex_avec_formatage(Rational(1, 2)) '\frac{1}{2}'
- Mes_fctions_generalistes_bis.pxsl_latex_with_formatting(expr, sign=False, display=True)[source]
en{LaTeX wrapper that applies number formatting.}
r{Wrapper LaTeX qui applique le formatage des nombres.}
en{This function converts an expression to LaTeX and applies special formatting for large numbers (>= 1000). It handles integers, floats, rational fractions, and general SymPy expressions.}
- r{Cette fonction convertit une expression en LaTeX et applique un formatage
spécial pour les grands nombres (>= 1000). Elle gère les entiers, flottants, fractions rationnelles et expressions SymPy.}
- exprint, float, sympy.Rational, or sympy.Expr
en{Expression to convert to LaTeX with formatting.}
- r{Expression à convertir en LaTeX avec formatage.}
- signbool, optional
en{If True, explicitly prefixes a sign (‘+’ or ‘-‘). Default: False.}
- r{Si True, préfixe explicitement un signe (‘+’ ou ‘-‘). Par défautFalse.}
- displaybool, optional
en{If True, uses displaystyle for the LaTeX output. Default: True.}
r{Si True, utilise displaystyle pour la sortie LaTeX. Par défaut : True.}
- str
en{The LaTeX string with number formatting applied.}
r{La chaîne LaTeX avec formatage appliqué.}
>>> pxsl_latex_with_formatting(1500) '1\ 500' >>> pxsl_latex_with_formatting(Rational(2000, 3)) '\frac{2\ 000}{3}' >>> pxsl_latex_with_formatting(Rational(1, 2)) '\frac{1}{2}'
- Mes_fctions_generalistes_bis.latex_coefficient(coeff, variable=None, sign=False, zeros=True, ones=False, display=True)[source]
Formats a coefficient for LaTeX display.
This function formats a coefficient for display in a LaTeX polynomial expression. It handles special cases where the coefficient is 1 or -1 and provides options for displaying signs, omitting zeros, or showing numerical ones.
- Parameters:
coeff (int, float, or sympy.Expr) – The coefficient to format.
sign (None or '+') – If ‘+’, a ‘+’ sign is displayed before the expression when it is positive.
variable (str or Symbol, optional) – Expression or variable attached to the coefficient (can be omitted if zeros=False).
zeros (bool, default True) – If False, the coefficient and its variable are not written when the coefficient is zero.
ones (bool, default False) – If False, -1 is written as ‘-’ and 1 as an empty string. If True, both -1 and 1 are kept as numeric values.
display (bool, optional) – Whether to produce display-mode LaTeX (used in the examples below).
- Returns:
The coefficient formatted for LaTeX. Returns an empty string for coeff=1, ‘-’ for coeff=-1, and the formatted representation otherwise.
- Return type:
str
Examples
>>> pxsl_latex_coefficient(1) '' >>> pxsl_latex_coefficient(-1, ones = True) '-1' >>> pxsl_latex_coefficient(-1) '-' >>> pxsl_latex_coefficient(5) '5' >>> pxsl_latex_coefficient(5, sign = True) '+5' >>> pxsl_latex_coefficient(1500) '1\ 500' >>> pxsl_latex_coefficient(0, variable = Symbol('L_1'), zeros = True) '0L_1' >>> pxsl_latex_coefficient(0, variable = Symbol('L_1'), zeros = False) '' >>> pxsl_latex_coefficient(Rational(-5, 2), sign = '+', display = False) '-\frac{5}{2}' >>> pxsl_latex_coefficient(Rational(-5, 2), sign='+') '-\displaystyle \frac{5}{2}'
- Mes_fctions_generalistes_bis.pxsl_latex_coefficient(coeff, variable=None, sign=False, zeros=True, ones=False, display=True)[source]
Formats a coefficient for LaTeX display.
This function formats a coefficient for display in a LaTeX polynomial expression. It handles special cases where the coefficient is 1 or -1 and provides options for displaying signs, omitting zeros, or showing numerical ones.
- Parameters:
coeff (int, float, or sympy.Expr) – The coefficient to format.
sign (None or '+') – If ‘+’, a ‘+’ sign is displayed before the expression when it is positive.
variable (str or Symbol, optional) – Expression or variable attached to the coefficient (can be omitted if zeros=False).
zeros (bool, default True) – If False, the coefficient and its variable are not written when the coefficient is zero.
ones (bool, default False) – If False, -1 is written as ‘-’ and 1 as an empty string. If True, both -1 and 1 are kept as numeric values.
display (bool, optional) – Whether to produce display-mode LaTeX (used in the examples below).
- Returns:
The coefficient formatted for LaTeX. Returns an empty string for coeff=1, ‘-’ for coeff=-1, and the formatted representation otherwise.
- Return type:
str
Examples
>>> pxsl_latex_coefficient(1) '' >>> pxsl_latex_coefficient(-1, ones = True) '-1' >>> pxsl_latex_coefficient(-1) '-' >>> pxsl_latex_coefficient(5) '5' >>> pxsl_latex_coefficient(5, sign = True) '+5' >>> pxsl_latex_coefficient(1500) '1\ 500' >>> pxsl_latex_coefficient(0, variable = Symbol('L_1'), zeros = True) '0L_1' >>> pxsl_latex_coefficient(0, variable = Symbol('L_1'), zeros = False) '' >>> pxsl_latex_coefficient(Rational(-5, 2), sign = '+', display = False) '-\frac{5}{2}' >>> pxsl_latex_coefficient(Rational(-5, 2), sign='+') '-\displaystyle \frac{5}{2}'
- Mes_fctions_generalistes_bis.to_rational_or_symbol(value)[source]
Convertit un nombre en Rational SymPy ou garde un symbole SymPy.
Cette fonction prend une valeur et la convertit en objet Rational de SymPy si c’est un nombre, ou la garde telle quelle si c’est déjà un symbole SymPy. Pour les flottants, elle utilise Fraction pour une conversion précise.
- Parameters:
value (int, float, sympy.Symbol, or sympy.Rational) – La valeur à convertir.
- Returns:
La valeur convertie en Rational si c’est un nombre, ou la valeur originale si c’est un symbole ou autre type.
- Return type:
sympy.Rational or sympy.Symbol or any
Examples
>>> from sympy import Symbol >>> x = Symbol('x') >>> to_rational_or_symbol(5) Rational(5, 1)
>>> to_rational_or_symbol(0.5) Rational(1, 2)
>>> to_rational_or_symbol(0.5) Rational(1, 2)
>>> to_rational_or_symbol(x) Symbol('x')
- Mes_fctions_generalistes_bis.pxsl_to_rational_or_symbol(value)[source]
en{Converts a number to a SymPy Rational or keeps a SymPy symbol as is.} fr{Convertit un nombre en Rational SymPy ou garde un symbole SymPy tel quel.}
en{This function takes a value and converts it into a SymPy Rational object if it is numeric, or keeps it unchanged if it is already a SymPy Symbol. For floats, it uses Python’s Fraction class to ensure a precise rational conversion.} fr{Cette fonction prend une valeur et la convertit en objet Rational de SymPy si c’est un nombre, ou la garde telle quelle si c’est déjà un symbole SymPy. Pour les flottants, elle utilise la classe Fraction de Python pour une conversion rationnelle précise.}
- Parameters:
value (int, float, sympy.Symbol, or sympy.Rational) – en{The value to convert.} fr{La valeur à convertir.}
- Returns:
en{The value converted to Rational if numeric, or the original value if it is a symbol or another type.} fr{La valeur convertie en Rational si c’est un nombre, ou la valeur originale si c’est un symbole ou un autre type.}
- Return type:
sympy.Rational or sympy.Symbol or any
Examples
>>> from sympy import Symbol >>> x = Symbol('x') >>> pxsl_to_rational_or_symbol(5) Rational(5, 1)
>>> pxsl_to_rational_or_symbol(0.5) Rational(1, 2)
>>> pxsl_to_rational_or_symbol(x) Symbol('x')
- Mes_fctions_generalistes_bis.resoudre_inequation_generale(a=1, b=0, c=0, variable='x', inegalite='>=', domaine='R', puissance=1, signe_a=None, detail_signe_a=False)[source]
Solves an inequality of the form ax^p + b ≥ c with detailed step-by-step reasoning in LaTeX.
This function solves linear (p=1) or quadratic (p=2) inequalities and generates a complete LaTeX-formatted solution showing all intermediate steps. It handles symbolic coefficients, different domains (real, integer, natural numbers), and cases where the sign of coefficient ‘a’ needs to be analyzed separately.
- Parameters:
a (int, float, or sympy expression, optional) – Coefficient of the variable term. Default is 1.
b (int, float, or sympy expression, optional) – Constant term on the left side. Default is 0.
c (int, float, or sympy expression, optional) – Constant term on the right side. Default is 0.
variable (str, optional) – Name of the variable. Default is “x”.
inegalite (str, optional) – Inequality symbol: “>=”, “>”, “<=”, or “<”. Default is “>=”.
domaine (str, optional) – Solution domain: “R” (reals), “Z” (integers), or “N” (natural numbers). Default is “R”.
puissance (int, optional) – Exponent of the variable: 1 (linear) or 2 (quadratic). Default is 1.
signe_a (str or None, optional) – Sign of coefficient ‘a’ when symbolic: “>” for positive, “<” for negative, or None to determine automatically. Default is None.
detail_signe_a (bool, optional) – Whether to explicitly mention the sign of ‘a’ when dividing. Default is False.
- Returns:
A tuple (solution_set, latex_reasoning) where: - solution_set : sympy set or dict
The solution set. Returns a dict with cases if the sign of ‘a’ or the right-hand side is undetermined.
- latex_reasoningstr
Complete LaTeX-formatted step-by-step solution.
- Return type:
tuple
- Raises:
ValueError – If inegalite is not in [“>=”, “>”, “<=”, “<”]. If domaine is not in [“R”, “Z”, “N”]. If puissance is not 1 or 2. If signe_a is not None, “>”, or “<”.
Examples
>>> # Simple linear inequality >>> sol, latex = resoudre_inequation_generale(2, 3, 7, variable="x", inegalite=">=") >>> print(sol) [2, oo)
>>> # Quadratic inequality >>> sol, latex = resoudre_inequation_generale(1, 0, 4, puissance=2, inegalite="<=") >>> print(sol) [-2, 2]
>>> # Integer domain >>> sol, latex = resoudre_inequation_generale(3, -1, 5, domaine="Z", inegalite=">") >>> print(sol) {3, 4, 5, ...}
>>> # Symbolic coefficient with sign analysis >>> from sympy import Symbol >>> a = Symbol('a') >>> sol, latex = resoudre_inequation_generale(a, 0, 5, inegalite=">=") >>> # Returns dict with cases for a>0 and a<0
- Mes_fctions_generalistes_bis.pxsl_solve_general_inequality(a=1, b=0, c=0, variable='x', inequality='>=', domain='R', power=1, sign_a=None, detail_sign_a=False)[source]
en{Solves an inequality of the form (a x^p + b ,square, c) with detailed step-by-step reasoning in LaTeX.} fr{Résout une inéquation de la forme (a x^p + b ,square, c) avec un raisonnement détaillé pas à pas en LaTeX.}
en{This function solves linear ((p=1)) or quadratic ((p=2)) inequalities and generates a complete LaTeX-formatted solution showing all intermediate steps. It handles symbolic coefficients, different domains (reals, integers, natural numbers), and cases where the sign of the coefficient (a) must be analyzed.} fr{Cette fonction résout des inéquations linéaires ((p=1)) ou quadratiques ((p=2)) et génère une solution complète au format LaTeX en détaillant toutes les étapes. Elle gère des coefficients symboliques, différents domaines (réels, entiers, naturels) et les cas où le signe du coefficient (a) doit être analysé.}
- Parameters:
a (int, float, or sympy expression, optional) – en{Coefficient of the variable term. Default: 1.} fr{Coefficient du terme en variable. Par défaut : 1.}
b (int, float, or sympy expression, optional) – en{Constant term on the left-hand side. Default: 0.} fr{Terme constant au membre de gauche. Par défaut : 0.}
c (int, float, or sympy expression, optional) – en{Constant term on the right-hand side. Default: 0.} fr{Terme constant au membre de droite. Par défaut : 0.}
variable (str, optional) – en{Name of the variable. Default: “x”.} fr{Nom de la variable. Par défaut : “x”.}
inequality (str, optional) – en{Inequality symbol: “>=”, “>”, “<=”, “<”. Default: “>=”.} fr{Symbole d’inégalité : “>=”, “>”, “<=”, “<”. Par défaut : “>=”.}
domain (str, optional) – en{Solution domain: “R” (reals), “Z” (integers), “N” (natural numbers). Default: “R”.} fr{Domaine des solutions : “R” (réels), “Z” (entiers), “N” (naturels). Par défaut : “R”.}
power (int, optional) – en{Exponent of the variable: 1 (linear) or 2 (quadratic). Default: 1.} fr{Exposant de la variable : 1 (linéaire) ou 2 (quadratique). Par défaut : 1.}
sign_a (str or None, optional) – en{Sign of the coefficient (a) when symbolic: “>” for positive, “<” for negative, or None to determine automatically.} fr{Signe du coefficient (a) quand il est symbolique : “>” pour positif, “<” pour négatif, ou None pour déterminer automatiquement.}
detail_sign_a (bool, optional) – en{Whether to explicitly mention the sign of (a) when dividing. Default: False.} fr{Indique s’il faut expliciter le signe de (a) lors d’une division. Par défaut : False.}
- Returns:
en{A tuple ((text{solution_set}, text{latex_reasoning})) where:} fr{Un tuple ((text{solution_set}, text{latex_reasoning})) où :} - solution_set : sympy set or dict
en{The solution set. Returns a dict with cases if the sign of (a) or the RHS is undetermined.} fr{L’ensemble des solutions. Retourne un dictionnaire par cas si le signe de (a) ou le membre droit est indéterminé.}
latex_reasoning : str en{Complete LaTeX-formatted step-by-step solution.} fr{Solution détaillée pas à pas au format LaTeX.}
- Return type:
tuple
- Raises:
ValueError – en{If inequality not in [“>=”, “>”, “<=”, “<”].} fr{Si inequality n’est pas dans [“>=”, “>”, “<=”, “<”].} en{If domain not in [“R”, “Z”, “N”].} fr{Si domain n’est pas dans [“R”, “Z”, “N”].} en{If power not in [1, 2].} fr{Si power n’est pas dans [1, 2].} en{If sign_a not in {None, “>”, “<”}.} fr{Si sign_a n’est pas dans {None, “>”, “<”}.}
Examples
>>> # Simple linear inequality >>> sol, latex = solve_general_inequality(2, 3, 7, variable="x", inequality=">=") >>> print(sol) [2, oo)
>>> # Quadratic inequality >>> sol, latex = solve_general_inequality(1, 0, 4, power=2, inequality="<=") >>> print(sol) [-2, 2]
>>> # Integer domain >>> sol, latex = solve_general_inequality(3, -1, 5, domain="Z", inequality=">") >>> print(sol) {3, 4, 5, ...}
>>> # Symbolic coefficient with sign analysis >>> from sympy import Symbol >>> a = Symbol('a') >>> sol, latex = solve_general_inequality(a, 0, 5, inequality=">=") >>> # Returns dict with cases for a>0 and a<0
- Mes_fctions_generalistes_bis.pxsl_latex(expr, reverse=False)[source]
Convertit une expression symbolique en représentation LaTeX.
- Parameters:
expr – Expression symbolique (probablement SymPy) à convertir
reverse (bool) – Si True, inverse l’ordre des termes dans l’expression
- Returns:
Représentation LaTeX de l’expression
- Return type:
str
Examples
>>> from sympy import symbols >>> x, y = symbols('x y')
# Conversion standard >>> expr = x**2 + 3*x - 5 >>> pxsl_latex(expr) ‘x^{2} + 3 x - 5’
# Conversion avec ordre inversé >>> pxsl_latex(expr, reverse=True) ‘- 5 + 3 x + x^{2}’
# Expression avec termes négatifs >>> expr2 = -2*x**2 + x - 7 >>> pxsl_latex(expr2, reverse=True) ‘- 7 + x - 2 x^{2}’
# Expression plus complexe >>> expr3 = x**3 - 2*x**2 + 3*x - 4 >>> pxsl_latex(expr3, reverse=True) ‘- 4 + 3 x - 2 x^{2} + x^{3}’
Note
La fonction utilise myst() pour l’interpolation des variables, ce qui suggère une intégration avec MyST (Markedly Structured Text).
- Mes_fctions_generalistes_bis.pxs_is_reductible_sqrt(x)[source]
fr : détermine si un nombre ou une expression est reductible en racine carrée en : determines if a number or an expression is reducible for square root
- Parameters:
x – nombre ou expression symbolique
- Returns:
True si x est simplifiable dans une racine carrée
- Return type:
bool
Examples
>>> pxs_is_reductible_sqrt(16) 'True' >>> pxs_is_reductible_sqrt(24) 'True' >>> pxs_is_reductible_sqrt(13) 'False' >>> pxs_is_reductible_sqrt(13/24) 'True'
>>> x = Symbol('x') >>> pxs_is_reductible_sqrt(4*x) 'True' >>> pxs_is_reductible_sqrt(x/4) 'True' >>> y = Symbol('y') >>> pxs_is_reductible_sqrt(x/(4*y)) 'True' >>> pxs_is_reductible_sqrt(3*x/(2*y)) 'False'
- Mes_fctions_generalistes_bis.pxsl_Rational(num, den, orientation='v', display=True)[source]
Builds a SymPy expression representing the rational fraction num/den, simplifying only the numeric parts while keeping the symbolic or irrational factors in place.
- numsympy.Expr, int, float
The numerator of the fraction. Can be numeric or symbolic (e.g., 3*pi, 2*x, etc.).
- densympy.Expr, int, float
The denominator of the fraction. Must not be zero.
- orientationstr, optional
Display orientation: ‘v’ for vertical (LaTeX-style fraction), or any other value for horizontal rendering. Default is ‘v’.
- displaybool, optional
If True, returns a formatted LaTeX string via myst() for visual display. If False, returns a raw LaTeX string. Default is True.
- sympy.Expr or str
A SymPy expression representing the simplified fraction, or a LaTeX string depending on the orientation and display parameters.
- ZeroDivisionError
If den equals zero.
>>> pxsl_Rational(3*pi, 6) \displaystyle{
rac{pi}{2}}
>>> x = Symbol('x') >>> pxsl_Rational(4*x, 8) \displaystyle{
rac{x}{2}}
>>> pxsl_Rational(3*pi, 6, orientation='h') \pi / 2
- Mes_fctions_generalistes_bis.pxs_ln(arg)[source]
Reduce the natural logarithm ln(arg) when the argument is a perfect power.
The function rewrites ln(m**k) as k*ln(m) whenever possible. If the argument cannot be reduced, the expression ln(arg) is returned unchanged.
- Parameters:
arg (sympy expression or int) – Argument of the natural logarithm.
- Returns:
A reduced logarithmic expression of the form k*ln(m) if applicable, otherwise ln(arg).
- Return type:
sympy expression
Examples
>>> pxs_ln(9) 2*ln(3)
>>> pxs_ln(12) ln(12)
>>> pxs_ln(1) ln(1)
>>> pxs_ln(72) 2*ln(6)
- Mes_fctions_generalistes_bis.pxs_is_factorable(expr) bool[source]
Determine whether a SymPy expression is factorable.
An expression is considered factorable if its factorized form is not equivalent to its expanded form.
- Parameters:
expr (sympy expression or str) – The expression to test.
- Returns:
True if the expression is factorable, False otherwise.
- Return type:
bool
Examples
>>> pxsl_is_factorable("x^2 - 1") True
>>> pxsl_is_factorable("x^2 + 1") False
>>> pxsl_is_factorable("2*x*(x+1)") False
- Mes_fctions_generalistes_bis.pxsl_quotient(num: sympy.Expr, den: sympy.Expr, sign: bool = True) str[source]
Formats a quotient in LaTeX using myst, with special handling depending on whether the numerator is equal to 1.
- Parameters:
num (sympy.Expr) – The numerator of the quotient.
den (sympy.Expr) – The denominator of the quotient.
sign (bool, optional) – If True, the sign of the expression is explicitly handled. Default is True.
- Returns:
A LaTeX-formatted string generated via myst, representing either the simplified quotient num/den or the product num * 1/den depending on the value of num.q.
- Return type:
str
Examples
Case 1 — numerator behaves like 1 (num.q == 1) The function returns a single lc(num/den, sign=sign) block.
>>> # Example setup (illustrative) >>> # num = 1, den = x + 1 >>> pxsl_quotient(num, den) '\n \\py{lc(num/den, sign = sign)}\n '
>>> # Same case, but without forcing sign handling >>> pxsl_quotient(num, den, sign=False) '\n \\py{lc(num/den, sign = sign)}\n '
Case 2 — general numerator (num.q != 1) The function returns lc(num, sign=sign) multiplied by 1/den.
>>> # Example setup (illustrative) >>> # num = 3*x, den = x + 1 >>> pxsl_quotient(num, den) '\n \\py{lc(num, sign = sign)}\\py{mult_A}\\frac{1}{\\py{latex(den)}}\n '
>>> # Same case, but without forcing sign handling >>> pxsl_quotient(num, den, sign=False) '\n \\py{lc(num, sign = sign)}\\py{mult_A}\\frac{1}{\\py{latex(den)}}\n '
- Mes_fctions_generalistes_bis.pxs_randint(mini, maxi, exclude=[])[source]
Returns a random integer between mini and maxi avoiding the element(s) in exclude. Exclude can be an integer or a collection of integers.
- Mes_fctions_generalistes_bis.pxs_nvirgzero(x)[source]
Fr : Fonction qui supprime .0 si le nombre a une valeur entière en le convertissant en int. En : Function that removes .0 if the number has an integer value by converting it to int.
Version 2
13/03/25
Vérification
Auteur : Ronan Vérificateurs : Delphine
Paramètres
x : nombre
Retour
- int ou float :
si le nombre a une valeur entière avec une précision de E-10, il est transformé en int, sinon il n’est pas modifié.
Fonction utilisée par
pxsl_res_num, pxs_simul_law, pxsl_sum_vector
- Mes_fctions_generalistes_bis.pxsl_res_num(x, dec=4, pourc=False, text=False, egal=True, dot=True)[source]
Fr : Formate un nombre pour l’affichage avec LaTeX, avec gestion d’approximation. En : Formats a number for display with LaTeX, with approximation handling.
Version 2
13/03/25
Vérification
Auteur : Ronan Vérificateurs : Delphine
- param x:
Nombre à formater
- type x:
float/str
- param dec:
Nombre de décimales pour l’arrondi (défaut: 4)
- type dec:
int
- param pourc:
Si True, affiche également le résultat en pourcentage (défaut: False)
- type pourc:
bool
- param text:
Si True, utilise un format texte plus descriptif (défaut: False)
- type text:
bool
- param egal:
Si False, affichera simplement le nombre sans = ou approx devant
- type egal:
bool
- returns:
Formule LaTeX formatée
- rtype:
str
Fonction utilisée par
Aucune fonction pyxiscience
Mes_fctions_generalistes
Created on Thu Mar 17 19:11:52 2022
@author: jlebovits
- Mes_fctions_generalistes.Replace(A, alpha, beta)[source]
Remplace alpha par beta dans A, qui sont tous les 3 de type string
- Mes_fctions_generalistes.prog_remplacement_mots_dans_une_liste(L, alpha, beta)[source]
alpha is replaced by beta in L -whether L is a list (of string) or a string -whether alpha and beta are a list (of string) or a string If L is a list liste L = [L[1], L[2], …, L[n]] such that L[i] are strings, then this script returns List L where in each string L[i], every word or character in alpha has been repladed by the corresponding word or caracter in beta
Mes_fctions_probabilistes_bis
Created on Thu Apr 04 2025
@author: Delphine
- Mes_fctions_probabilistes_bis.pxsl_pow(x, n=1, opt=0, displaystyle=True)[source]
Fonction permettant d’écrire le nombre x entouré de parenthèses lorsqu’il est négatif ou irrationnel avec deux termes (par ex : 1+sqrt(2) ou 3sqrt(2)) Ne fonctionne pas pour des valeurs numériques non simplifiées (par ex : 1+3 ou 3*3/2)
Version
13/02/25
Paramètres
- xnombre ou expression
La base à élever à la puissance n
- nint, optional
L’exposant (défaut: 1)
- optint, optional
Option de formatage (défaut: 0) 0: formatage standard 1: simplifie l’affichage pour x=1, x=0 ou n=1 2: simplifie davantage et renvoie une chaîne vide pour x=0
- displaystylebool, optional
Si True, utilise displaystyle pour les fractions (défaut: False)
Retour
- str
retourne l’expression en latex
- Mes_fctions_probabilistes_bis.pxs_nvirgzero(x)[source]
Fr : Fonction qui supprime .0 si le nombre a une valeur entière en le convertissant en int. En : Function that removes .0 if the number has an integer value by converting it to int.
Version 2
13/03/25
Vérification
Auteur : Ronan Vérificateurs : Delphine
Paramètres
x : nombre
Retour
- int ou float :
si le nombre a une valeur entière avec une précision de E-10, il est transformé en int, sinon il n’est pas modifié.
Fonction utilisée par
pxsl_res_num, pxs_simul_law, pxsl_sum_vector
- Mes_fctions_probabilistes_bis.pxsl_res_num(x, dec=4, pourc=False, text=False, egal=True, dot=True)[source]
Fr : Formate un nombre pour l’affichage avec LaTeX, avec gestion d’approximation. En : Formats a number for display with LaTeX, with approximation handling.
Version 2
13/03/25
Vérification
Auteur : Ronan Vérificateurs : Delphine
- param x:
Nombre à formater
- type x:
float/str
- param dec:
Nombre de décimales pour l’arrondi (défaut: 4)
- type dec:
int
- param pourc:
Si True, affiche également le résultat en pourcentage (défaut: False)
- type pourc:
bool
- param text:
Si True, utilise un format texte plus descriptif (défaut: False)
- type text:
bool
- param egal:
Si False, affichera simplement le nombre sans = ou approx devant
- type egal:
bool
- returns:
Formule LaTeX formatée
- rtype:
str
Fonction utilisée par
Aucune fonction pyxiscience
- Mes_fctions_probabilistes_bis.pxsl_scalar_product(a, b, prod='times', displaystyle=True)[source]
Fr : Fonction permettant d’écrire le calcul du produit scalaire entre les deux vecteurs a et b. En : Function to calculate the dot product between two vectors a and b.
Version 1
02/03/25
Vérification
Auteur : Ronan Vérificateurs : Delphine
Paramètres
- aliste
Premier vecteur du produit
- bliste
Deuxième vecteur du produit
- prodstr
times : le symbole produit est imes dot : le symbole produit est cdot
Retour
- str
retourne l’expression en latex
Fonction utilisée par
Aucune fonction pyxiscience
- Mes_fctions_probabilistes_bis.pxsl_moment(X, n=1, prod='times', displaystyle=True)[source]
Fr : Fonction permettant d’écrire le calcul du moment d’ordre n de la variable aléatoire finie X. En : Function to calculate the nth order moment of the finite random variable X.
Version 1
02/03/25
Vérification
Auteur : Ronan Vérificateurs : Delphine
Paramètres
X : variable aléatoire finie
- nint
Ordre du moment
- prodstr
times : le symbole produit est imes dot : le symbole produit est cdot
Retour
- str
retourne l’expression en latex
Fonction utilisée par
Aucune fonction pyxiscience
- Mes_fctions_probabilistes_bis.pxsl_law(textx, textprob, X, frac='', nzero=True)[source]
Fr : Fonction permettant d’écrire le tableau de loi d’une variable aléatoire X finie. En : Function to write the probability distribution table of a finite random variable X.
02/03/25
Auteur : Ronan Vérificateurs : Delphine
- textxstr
Entrée de la première ligne du tableau de loi (valeurs possibles) Peut contenir du LaTeX directement (sans échappement)
- textprobstr
Entrée de la deuxième ligne du tableau de loi (probabilités) Peut contenir du LaTeX directement (sans échappement)
- Xvariable aléatoire finie
Variable aléatoire dont on veut afficher la loi
- fracstr, optional
“/” : les fractions sont représentées avec / (notation simple) “” : les fractions sont représentées avec la commande
rac{}{} (défaut)
- nzeroboolean, optional
True : les probabilités nulles ne sont pas représentées (défaut) False : les probabilités nulles sont représentées
- str
Retourne un tableau LaTeX contenant la loi de probabilité
Aucune fonction pyxiscience
- Mes_fctions_probabilistes_bis.pxs_simul_law(n, type_proba='dec', prec=0.01, nzero=True)[source]
Fr : Fonction permettant de simuler une loi de probabilité discrète de taille n. En : Function to simulate a discrete probability distribution of size n.
Version 1
02/03/25
Vérification
Auteur : Ronan Vérificateurs : Delphine
Paramètres:
- nint
Nombre de valeurs possibles de la loi
- type_probastr
Format des probabilités générées - “dec” : nombres décimaux (entre 0 et 1) - “perc” : pourcentages (entre 0 et 100) - “frac” : fractions
- precfloat ou int
Si type==”dec” ou “perc” : les probabilités seront des multiples de prec
Si type==”frac” : prec est un entier, les probabilités seront des multiples de 1/prec
- nzerobool
True : les probabilités seront non nulles si possible
False : les probabilités peuvent être nulles
Retour:
- list
Liste des probabilités (la somme vaut 1 ou 100 selon le type)
Fonction utilisée par
Aucune fonction pyxiscience
- Mes_fctions_probabilistes_bis.pxs_fct_finiterv(f, X)[source]
Fr : Transforme une variable aléatoire finie X via une fonction f. Cette fonction crée une nouvelle variable aléatoire Y = f(X) en appliquant la fonction f à chaque valeur possible de X et en adaptant les probabilités. En : Transforms a finite random variable X using a function f. This function creates a new random variable Y = f(X) by applying the function f to each possible value of X and adapting the probabilities accordingly.
Version 1
02/03/25
Vérification
Auteur : Ronan Vérificateurs : Delphine
Paramètres
- ffunction
Fonction à appliquer à la variable aléatoire X
- XRandomSymbol
Variable aléatoire finie source
Retour
- RandomSymbol
Variable aléatoire finie Y = f(X)
Fonction utilisée par
Aucune fonction pyxiscience
- Mes_fctions_probabilistes_bis.pxsl_sum_vector(x)[source]
Fr : Fonction permettant d’écrire la somme des éléments du vecteur x En: Function to calculate the sum of elements in vector x
Version
02/03/25
Vérification
Auteur : Ronan Vérificateurs : Delphine
Paramètres
x : liste
Retour
- str
retourne la somme de la liste de x
Fonction utilisée par
Aucune fonction pyxiscience
- Mes_fctions_probabilistes_bis.pxs_finiterv(x, val, prob)[source]
Fr : Fonction permettant de créer la variables aléatoire x dont les valeurs sont val et les probabilités associées sont prob. En: Function to create the random variable x whose values are val and the associated probabilities are prob.
Version
02/03/25
Vérification
Auteur : Ronan Vérificateurs : Delphine
Paramètres
x : liste
Retour
variable aléatoire
Fonction utilisée par
Aucune fonction pyxiscience
Mes_fctions_probabilistes_new
- Mes_fctions_probabilistes_new.randnbres(n, p)[source]
Retourne une liste de n rationnels, tirés aléatoirement entre 0 et p, mais dont la somme vaut 1
Paramètres: - n (int): Nombre de valeurs rationnelles à générer - p (int): Borne supérieure pour les valeurs aléatoires (exclusif)
Retourne: - list: Liste de n rationnels dont la somme est égale à 1
- Mes_fctions_probabilistes_new.randnbresstrictpositifs(n, k, p)[source]
Retourne une liste de n entiers, tirés aléatoirement entre k et p
Paramètres: - n (int): Nombre d’entiers à générer - k (int): Borne inférieure (incluse) - p (int): Borne supérieure (exclue)
Retourne: - list: Liste de n entiers aléatoires dans l’intervalle [k, p-1]
- Mes_fctions_probabilistes_new.Multiple_of_p_in_L(p, L)[source]
Créer, à partir de la liste L, une liste ne contenant que les élements de L qui sont divisibles par p
Paramètres: - p (int): Le diviseur - L (list): Liste d’entiers à filtrer
Retourne: - list: Liste des éléments de L divisibles par p
- Mes_fctions_probabilistes_new.rand_p_proba_a_partir_list(p, L)[source]
Retourne une liste composée de p éléments de la liste initiale L, pris au hasard (uniformément)
Paramètres: - p (int): Nombre d’éléments à sélectionner - L (list): Liste source
Retourne: - list: Une liste de p éléments tirés au hasard de L
- Mes_fctions_probabilistes_new.Test_proba_pris_in_list(L, ind, p, nber_max, Lpartielle)[source]
Teste si le nombre L[ind] peut être choisi comme valeur d’une probabilité.
Cette fonction vérifie si L[ind] peut être accepté comme poids d’une probabilité en tenant compte de: - La somme totale des poids, qui ne doit pas dépasser nber_max (pour pouvoir renormaliser) - Il faut avoir p probabilités au total - On a déjà sélectionné len(Lpartielle) poids
Paramètres: - L (list): Liste des valeurs possibles pour les poids - ind (int): Indice du poids à tester dans L - p (int): Nombre total de probabilités à générer - nber_max (int/float): Valeur maximale pour la somme des poids - Lpartielle (list): Liste des poids déjà sélectionnés
Retourne: - int: 1 si L[ind] peut être accepté, 0 sinon
- Mes_fctions_probabilistes_new.Poids_d_une_proba_in_list(Linit, p, nber_max)[source]
Renvoie une liste de p poids, pris dans la liste Linit dont la somme vaut nber_max, pour autant que ce soit possible
Paramètres: - Linit (list): Liste des valeurs possibles pour les poids - p (int): Nombre de poids à sélectionner - nber_max (int/float): Valeur cible pour la somme des poids
Retourne: - list: Liste de p poids dont la somme est nber_max, ou None si impossible
- Mes_fctions_probabilistes_new.nor(x)[source]
Calcule la densité de la loi normale standard N(0,1) au point x.
Paramètre: - x (float): Point où évaluer la densité
Retourne: - float: Valeur de la densité de probabilité en x
- Mes_fctions_probabilistes_new.fctionofafiniteRV(f, X)[source]
Crée une nouvelle variable aléatoire finie Y = f(X) à partir d’une variable aléatoire finie X existante et d’une fonction f.
Parameters:
- fcallable
La fonction à appliquer à la variable aléatoire X
- XRandomSymbol
Une variable aléatoire finie (de type FiniteRV)
Returns:
- RandomSymbol
La nouvelle variable aléatoire Y = f(X) Si la somme des probabilités n’est pas égale à 1, retourne un message d’erreur
Example:
>>> from sympy.stats import FiniteRV, density >>> from sympy import Rational >>> X = FiniteRV('X', {0: Rational(1, 3), 1: Rational(2, 3)}) >>> Y = fctionofafiniteRV(lambda x: x**2, X) >>> density(Y).dict {0: Rational(1, 3), 1: Rational(2, 3)}
- Mes_fctions_probabilistes_new.ExpandFiniteRV(f, X, name_of_f_of_X_for_LaTeX, ponctu='')[source]
Génère une représentation LaTeX de la distribution de probabilité de f(X).
Parameters:
- fcallable
La fonction à appliquer à la variable aléatoire X
- XRandomSymbol
Une variable aléatoire finie
- name_of_f_of_X_for_LaTeXstr
Nom à utiliser pour f(X) dans la sortie LaTeX
- ponctustr, optional
Type de ponctuation à utiliser (‘point’, ‘virg’, ou ‘’)
Returns:
- str
La représentation LaTeX de la distribution de probabilité de f(X)
- Mes_fctions_probabilistes_new.ExpandExpFiniteRV(f, X, name_of_the_original_rv, latex_name_of_f_of_alpha, name_funct_and_name_rv, ponctu='')[source]
Génère une représentation LaTeX du calcul de l’espérance E[f(X)], où X est une variable aléatoire finie.
Parameters:
- fcallable
La fonction à appliquer à la variable aléatoire X
- XRandomSymbol
Une variable aléatoire finie
- name_of_the_original_rvstr
Nom de la variable aléatoire X pour l’affichage LaTeX
- latex_name_of_f_of_alphastr
Représentation LaTeX de f(alpha)
- name_funct_and_name_rvstr
Représentation LaTeX de f(X) pour l’en-tête E[f(X)]
- ponctustr, optional
Type de ponctuation à utiliser (‘point’, ‘virg’, ou ‘’)
Returns:
- str
La représentation LaTeX du calcul de E[f(X)]
- Mes_fctions_probabilistes_new.ComputeExpFiniteRV(f, X)[source]
Calcule l’espérance mathématique E[f(X)] pour une variable aléatoire finie X.
Cette fonction est un cas particulier de ComputeExp_p_FiniteRV avec p=1.
Parameters:
- fcallable
La fonction à appliquer à la variable aléatoire X
- XRandomSymbol
Une variable aléatoire finie
Returns:
- sympy.Expr
L’espérance E[f(X)]
Example:
>>> from sympy import Rational >>> from sympy.stats import FiniteRV >>> X = FiniteRV('X', {1: Rational(1, 4), 2: Rational(1, 2), 3: Rational(1, 4)}) >>> ComputeExpFiniteRV_optimized(lambda x: x**2, X) # E[X^2] Rational(5, 2)
- Mes_fctions_probabilistes_new.VarFiniteRV(f, X)[source]
Calcule la variance Var(f(X)) d’une variable aléatoire finie X transformée par une fonction f.
Utilise la formule: Var(f(X)) = E[f(X)²] - E[f(X)]²
Parameters:
- fcallable
La fonction à appliquer à la variable aléatoire X
- XRandomSymbol
Une variable aléatoire finie
Returns:
- sympy.Expr
La variance de f(X)
Example:
>>> from sympy import Rational >>> from sympy.stats import FiniteRV >>> X = FiniteRV('X', {1: Rational(1, 2), 2: Rational(1, 2)}) >>> VarFiniteRV_optimized(lambda x: x**2, X) Rational(9, 4)
- Mes_fctions_probabilistes_new.ComputeExp_p_FiniteRV(f, X, p)[source]
Calcule l’espérance mathématique E[f(X)^p] pour une variable aléatoire finie X, une fonction f et un exposant p.
Parameters:
- fcallable
La fonction à appliquer à la variable aléatoire X
- XRandomSymbol
Une variable aléatoire finie
- pint or float
L’exposant à appliquer au résultat de f(X)
Returns:
- sympy.Expr
L’espérance E[f(X)^p]
Example:
>>> from sympy import Rational >>> from sympy.stats import FiniteRV >>> X = FiniteRV('X', {1: Rational(1, 3), 2: Rational(2, 3)}) >>> ComputeExp_p_FiniteRV_optimized(lambda x: x, X, 2) # E[X^2] Rational(5, 3)
- Mes_fctions_probabilistes_new.randnbresstrictpositifsreel(n, k, p, s)[source]
Génère une liste de n nombres réels positifs aléatoires.
Parameters:
- nint
Nombre de valeurs à générer
- kint
Borne inférieure pour la partie entière des nombres
- pint
Borne supérieure pour la partie entière des nombres (non incluse)
- sint
Nombre de chiffres significatifs après la virgule (Note: la fonction actuelle utilise toujours 1 décimale indépendamment de s)
Returns:
- list
Liste de n nombres réels aléatoires entre k et p avec des décimales
Example:
>>> from sympy.stats import DiscreteUniform, sample_iter >>> randnbresstrictpositifsreel_optimized(5, 1, 10, 1) [1.7, 3.4, 7.9, 2.3, 8.6] # Résultat exemple avec des valeurs aléatoires
Mes_fctions_probabilistes
Created on Thu Mar 17 19:11:52 2022
@author: jlebovits
- Mes_fctions_probabilistes.randnbres(n, p)[source]
Retourne une liste de n rationnels, tirés aléatoirement entre 0 et p, mais dont la somme vaut 1
- Mes_fctions_probabilistes.randnbresstrictpositifs(n, k, p)[source]
Retourne une liste de n entiers, tirés aléatoirement entre k et p
- Mes_fctions_probabilistes.randnbres_in_L(p, L, Lprime=[])[source]
EN: Returns a list composed of p elements of the initial list L, taken at random (uniformly) and which do not belng to Lprime. By default, Lprime is empty. # FR: Retourne une liste composée de p élements de la liste initiale L, pris au hasard (uniformément) et qui ne sont pas dans la liste Lprime. Par défaut, Lprime est vide.
- Mes_fctions_probabilistes.Multiple_of_p_in_L(p, L)[source]
Créer, à partir de la liste L, une liste ne contenant que les élements de L qui sont divisibles par p
- Mes_fctions_probabilistes.rand_p_proba_a_partir_list(p, L)[source]
Retourne une liste composée de p élements de la liste initiale L, pris au hasard (uniformément)
- Mes_fctions_probabilistes.Test_proba_pris_in_list(L, ind, p, nber_max, Lpartielle)[source]
teste si le nbre L[ind] peut-être choisi comme valeur d’une proba sachant que l’on doit avoir au total, à la fin, p proba tirées dans L, la somme totale ne doit pas dépasser nber_max (car on renormalisera
en divisant tous les poids par nber_max à la fin)
et que pour l’instant on a déjà tireés len(Lpartielle) nbres pour les poids précédents. La somme de tous les poids devra valoir nber_max. Cette fction renvoie 1 si L[ind] peut-être acceptée comme poids d’une proba et 0 sinon. EN fait on teste deux choses:
la somme des poids précédents + L[ind] ne dépasse pas nber_max
- la somme des poids précédents + L[ind] + (q-N_partiel)*L[0]
ne dépasse pas nber_max (i.e. la somme de tous les poids précédemment choisis + le poids L[ind] + tous les poids futurs (en prenant le min possible pour chacun) ne dépasse pas nber_max
- Mes_fctions_probabilistes.Poids_d_une_proba_in_list(Linit, p, nber_max)[source]
Renvoie une liste de poids, pris dans la liste Linit dont la somme vaut nber_max, pour autant que ce soit possible
- Mes_fctions_probabilistes.fctionofafiniteRV(f, X)[source]
Pour une va finie donnée, notée X, et une fction notée f, on définit la v.a. finie f(X) et donc un nom (de la classe sympy.stats.rv.RandomSymbol) et un dictionnaire (de la classe dict). Le nom est:
f_of_X (où f et X sont remplacées par les vrais noms de la v.a. X et de la fction f), accessible via fctionofafiniteRV(f,X,pdfX)
dont le dictionnaire est accessible via density(fctionofafiniteRV(f,X)).dict
- Mes_fctions_probabilistes.ExpandFiniteRV(f, X, name_of_f_of_X_for_LaTeX, ponctu)[source]
“ pr LaTeX Met dans un align la distribution de la v.a. finie X
- Mes_fctions_probabilistes.ExpandExpFiniteRV(f, X, name_of_the_original_rv, latex_name_of_f_of_alpha, name_funct_and_name_rv, ponctu)[source]
“ Met dans un align le calcul de l’espérance de f(X) i.e. E[f(X)], où X une v.a. finie.
- Mes_fctions_probabilistes.ComputeExpFiniteRV(f, X)[source]
“ Calcule l’espérance E[f(X)], où X une v.a. finie. Je pense que c’est maintenant devenu une fction inutile
- Mes_fctions_probabilistes.VarFiniteRV(f, X)[source]
“ Calcul de la variance de f(X), où X une v.a. finie.
- Mes_fctions_probabilistes.ComputeExp_p_FiniteRV(f, X, p)[source]
“ Calcule l’espérance E[f(X)^p], où X une v.a. finie.
- Mes_fctions_probabilistes.ExpandFiniteRV_V2(f, X, name_of_the_original_rv, name_funct_and_name_rv, ponctu)[source]
“ Met dans un align unique la distribution de la v.a. finie f(X), en les rangeant 4 par 4