equadifff.py

Created by teivaetienne

Created on January 29, 2026

10.6 KB


from math import *

# PROG: PREPA-INGENIEUR V13
# EDITION "PROFESSEUR" (BAVARD)
# EXPLICATIONS DETAILLEES INCLUSES

def arr(x):
  return round(x, 3)

def sep():
  # Ligne de separation
  print("-" * 40)

def tit(t):
  # Titre centre manuellement
  print("\n")
  sep()
  lg_ecran = 40
  lg_texte = len(t)
  marge = (lg_ecran - lg_texte) // 2
  if marge < 0: marge = 0
  print(" " * marge + t)
  sep()

def pause():
  input("  [Appuie sur EXE pour lire la suite]")

# --- 1. SOLVEUR EQUA DIFF ---
def equa_diff():
  tit("SOLVEUR EQUATIONS DIFF.")
  print("Ce programme va resoudre pas a pas")
  print("l'equation : a.y'' + b.y' + c.y = f(t)")
  sep()
  
  try:
    a = float(input("Coefficient a : "))
    b = float(input("Coefficient b : "))
    c = float(input("Coefficient c : "))
  except: return

  # --- ETAPE 1: HOMOGENE ---
  print("\n--- ETAPE 1 : HOMOGENE (yh) ---")
  print("D'abord, on eteint le second membre.")
  print("On resout : " + str(a) + "r^2 + " + str(b) + "r + " + str(c) + " = 0")
  
  D = b*b - 4*a*c
  print("J'ai calcule le discriminant Delta.")
  print("Delta = " + str(arr(D)))
  
  m, r1, r2, alp, bet = 0,0,0,0,0
  
  if D > 0:
    m = 1
    r1 = (-b - sqrt(D)) / (2*a)
    r2 = (-b + sqrt(D)) / (2*a)
    print("Delta > 0, donc 2 solutions reelles.")
    print("Cela correspond a un regime aperiodique.")
    print("r1 = " + str(arr(r1)))
    print("r2 = " + str(arr(r2)))
    print("Forme yh(t) : A*exp(r1*t) + B*exp(r2*t)")
    
  elif D == 0:
    m = 2
    r1 = -b / (2*a)
    print("Delta = 0, donc 1 solution double.")
    print("C'est le regime critique.")
    print("r0 = " + str(arr(r1)))
    print("Forme yh(t) : (A*t + B) * exp(r0*t)")
    
  else:
    m = 3
    alp = -b / (2*a)
    bet = sqrt(-D) / (2*a)
    print("Delta < 0, donc solutions complexes.")
    print("Cela correspond a un regime oscillant.")
    print("Partie Reelle (Amorti) = " + str(arr(alp)))
    print("Partie Imag   (Oscill) = " + str(arr(bet)))
    print("Forme yh(t) :")
    print("exp(at) * [A.cos(bt) + B.sin(bt)]")

  pause()

  # --- ETAPE 2: PARTICULIERE ---
  print("\n--- ETAPE 2 : PARTICULIERE (yp) ---")
  print("Maintenant, on s'occupe de f(t).")
  print("Quelle est sa forme ?")
  print("1 : Constante (ex: = 10)")
  print("2 : Harmonique (ex: 3*cos(2t))")
  print("3 : Polynome (ex: 5t^2 - 4t + 2)")
  ch = input("Ton choix : ")
  
  yp0, vp0 = 0, 0
  txt_yp = ""

  if ch == "1":
    print("-> Tu as choisi CONSTANTE.")
    K = float(input("Quelle est sa valeur K ? "))
    print("On cherche une solution constante yp = C.")
    if c != 0:
      yp0 = K / c
      txt_yp = "+ " + str(arr(yp0))
      print("En injectant dans l'equation : c*yp = K")
      print("Donc yp = K/c = " + str(arr(yp0)))
    else: print("Impossible car c=0 (Cas rare).")

  elif ch == "2":
    print("-> Tu as choisi HARMONIQUE.")
    F = float(input("Amplitude F : "))
    w = float(input("Pulsation w : "))
    print("On cherche yp = A.cos(wt) + B.sin(wt)")
    print("Je passe par les complexes pour trouver A et B...")
    
    den = (c - a*w*w)**2 + (b*w)**2
    if den == 0:
      print("/!\\ ALERTE RESONANCE /!\\")
      print("w excitation = w propre du systeme.")
      print("La solution explose en t * sin(wt).")
      txt_yp = "+ RESONANCE (Voir cours)"
    else:
      re = c - a*w*w
      im = b*w
      C1 = (F * re) / den
      C2 = (F * im) / den
      yp0, vp0 = C1, C2*w
      
      print("Resultat de l'identification :")
      print("Coef devant Cos = " + str(arr(C1)))
      print("Coef devant Sin = " + str(arr(C2)))
      
      sig = "+" if C2 >= 0 else ""
      txt_yp = "+" + str(arr(C1)) + "cos(" + str(w) + "t)"
      txt_yp += "\n" + sig + str(arr(C2)) + "sin(" + str(w) + "t)"

  elif ch == "3":
    print("-> Tu as choisi POLYNOME.")
    print("f(t) est de la forme P*t^2 + Q*t + R")
    print("Remplis les cases (mets 0 si absent) :")
    try:
      P = float(input("P (coeff t^2) : "))
      Q = float(input("Q (coeff t)   : "))
      R = float(input("R (constante) : "))
      
      sep()
      print("ANALYSE DU POLYNOME :")
      degre = 0
      if P != 0: degre = 2
      elif Q != 0: degre = 1
      
      if degre == 2:
        print("C'est du second degre (Parabole).")
        print("Je cherche yp = A.t^2 + B.t + C")
      elif degre == 1:
        print("C'est du premier degre (Lineaire).")
        print("Comme P=0, je cherche juste yp = B.t + C")
      else:
        print("C'est une constante (Degre 0).")
        print("Je cherche yp = C")
      
      sep()
      
      if c != 0:
        # Identification mathématique
        A_p = P / c
        B_p = (Q - 2*b*A_p) / c
        C_p = (R - 2*a*A_p - b*B_p) / c
        yp0, vp0 = C_p, B_p # Pour les CI plus tard
        
        print("J'ai identifie les coefficients :")
        if degre == 2:
          print("A (devant t^2) = " + str(arr(A_p)))
        if degre >= 1:
          print("B (devant t)   = " + str(arr(B_p)))
        print("C (constante)  = " + str(arr(C_p)))
        
        txt_yp = "+" + str(arr(A_p)) + "t^2+" + str(arr(B_p)) + "t+" + str(arr(C_p))
      else:
        print("Erreur: c=0 (le degre monterait de 1)")
    except: pass

  pause()

  # --- ETAPE 3: C.I. ---
  print("\n--- ETAPE 3 : CONDITIONS INITIALES ---")
  print("Il me faut les conditions de depart")
  print("pour trouver les constantes A et B.")
  try:
    y_start = float(input("y(0) (Position) : "))
    v_start = float(input("y'(0) (Vitesse) : "))
  except: return

  # Correction
  print("Calcul du systeme lineaire...")
  Y = y_start - yp0
  V = v_start - vp0
  AA, BB = 0, 0
  
  if m == 1:
    if r1 != r2:
      AA = (V - r2*Y) / (r1 - r2)
      BB = Y - AA
  elif m == 2:
    BB = Y
    AA = V - BB*r1
  elif m == 3:
    AA = Y
    if bet != 0: BB = (V - AA*alp) / bet

  # --- AFFICHAGE FINAL ---
  tit("CONCLUSION / REDACTION")
  print("Voici la solution unique y(t).")
  print("Recopie ces coefficients :")
  print("A = " + str(arr(AA)))
  print("B = " + str(arr(BB)))
  sep()
  print("SOLUTION FINALE y(t) = ")
  
  if m == 1:
    print(str(arr(AA)) + " * exp(" + str(arr(r1)) + "t)")
    sig = "+" if BB >= 0 else ""
    print(sig + str(arr(BB)) + " * exp(" + str(arr(r2)) + "t)")
    
  elif m == 2:
    sig = "+" if BB >= 0 else ""
    print("(" + str(arr(AA)) + "t " + sig + str(arr(BB)) + ")")
    print(" * exp(" + str(arr(r1)) + "t)")
    
  elif m == 3:
    print("exp(" + str(arr(alp)) + "t) * [")
    print(str(arr(AA)) + "cos(" + str(arr(bet)) + "t)")
    sig = "+" if BB >= 0 else ""
    print(sig + str(arr(BB)) + "sin(" + str(arr(bet)) + "t) ]")

  if txt_yp != "":
    print("\nN'oublie pas la sol. particuliere :")
    print(txt_yp)
    
  sep()
  print("Termine. Bon courage !")
  input("EXE pour Menu...")

# --- 2. INTEGRALES ---
def integrales():
  while True:
    tit("METHODOLOGIE INTEGRALES")
    print("Ici, on ne fait pas que calculer.")
    print("On apprend a rediger.")
    sep()
    print("1. I.P.P (Guide complet)")
    print("2. Jacobien (Aide-memoire)")
    print("3. Simpson (Verif calculatrice)")
    print("4. Retour")
    c = input("Choix : ")
    
    if c == "4": break
    
    elif c == "1":
      print("\n--- INTEGRATION PAR PARTIES ---")
      print("La formule a connaitre par coeur :")
      print("Int(u * v') = [uv] - Int(u'v)")
      sep()
      print("LE PROBLEME : Qui est u ? Qui est v' ?")
      print("LA SOLUTION : La regle ALPES.")
      print("Dans ton integrale, regarde les fonctions.")
      print("Choisis pour 'u' celle qui est la plus")
      print("HAUTE dans cette liste :")
      sep()
      print(" 1. A : Arcsin, Arccos, Arctan")
      print(" 2. L : Logarithme (ln)")
      print(" 3. P : Polynome (t, t^2, 1...)")
      print(" 4. E : Exponentielle (exp)")
      print(" 5. S : Sinus / Cosinus")
      sep()
      print("EXEMPLE : Int( t * exp(t) )")
      print("-> t est un Polynome (P)")
      print("-> exp est une Exponentielle (E)")
      print("P est avant E dans ALPES.")
      print("Donc tu poses u(t) = t")
      print("Et v'(t) = exp(t)")
      pause()
      
    elif c == "2":
      print("\n--- JACOBIENS (Chgt Variable) ---")
      print("Quand on change de variable dans une")
      print("integrale multiple, l'element dxdy change.")
      print("Il faut le multiplier par le Jacobien.")
      sep()
      print("1. POLAIRE (Disque)")
      print("   On pose x=r.cos(t) et y=r.sin(t)")
      print("   Le Jacobien vaut : r")
      print("   dx dy deviens -> r dr dt")
      sep()
      print("2. SPHERIQUE (Boule)")
      print("   Le Jacobien vaut : rho^2 * sin(phi)")
      print("   dV deviens -> rho^2 sin(phi) dr dph dth")
      pause()
      
    elif c == "3":
      print("\n--- VERIFICATEUR (SIMPSON) ---")
      print("Je vais calculer l'integrale a ta place")
      print("pour que tu verifis ton resultat.")
      try:
        a = float(input("Borne du bas a : "))
        b = float(input("Borne du haut b : "))
        print("Calcule f(x) pour :")
        print("x = " + str(arr(a)))
        ya = float(input(" -> f(a) = "))
        print("x = " + str(arr(b)))
        yb = float(input(" -> f(b) = "))
        mi = (a+b)/2
        print("x = " + str(arr(mi)) + " (le milieu)")
        ym = float(input(" -> f(m) = "))
        
        res = ((b-a)/6) * (ya + 4*ym + yb)
        sep()
        print("VALEUR EXACTE APPROCHEE = " + str(res))
        print("Si tu trouves pareil, c'est gagne.")
      except: pass
      pause()

# --- 3. PHYSIQUE ---
def physique():
  tit("OSCILLATEUR HARMONIQUE")
  print("Analyse physique de l'equation.")
  try:
    k = float(input("Coeff devant x (w0^2): "))
    f = float(input("Coeff devant x' (f)  : "))
    
    w0 = sqrt(abs(k))
    Q = 9999
    if f != 0: Q = w0 / f
    xi = 1 / (2*Q)
    
    print("\n--- PARAMETRES ---")
    print("Pulsation propre w0 = " + str(arr(w0)))
    print("Facteur Qualite  Q  = " + str(arr(Q)))
    print("Amortissement    xi = " + str(arr(xi)))
    sep()
    
    print("--- INTERPRETATION ---")
    if xi < 1:
      print("-> REGIME PSEUDO-PERIODIQUE")
      print("   Il y a des oscillations !")
      print("   Mais elles diminuent avec le temps.")
      wp = w0 * sqrt(1 - xi*xi)
      print("   Pulsation reelle w_p = " + str(arr(wp)))
    elif xi > 1:
      print("-> REGIME APERIODIQUE")
      print("   Trop de frottements.")
      print("   Pas d'oscillation possible.")
    else:
      print("-> REGIME CRITIQUE")
      print("   Limite juste entre les deux.")
  except: pass
  pause()

# --- BOUCLE PRINCIPALE ---
while True:
  tit("MENU INGENIEUR V13 (PROF)")
  print("1. Equa Diff (Le grand classique)")
  print("2. Integrales (Methodes & Verif)")
  print("3. Physique (Oscillateurs)")
  print("4. Quitter")
  
  ch = input("Choix : ")
  if ch == "1": equa_diff()
  elif ch == "2": integrales()
  elif ch == "3": physique()
  elif ch == "4": break

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.