import numpy as np
import matplotlib.pyplot as plt

# Equation de la réaction
"""
HSCN + IO4- → SCN- + HIO4
"""
#%% Conditions initiales
c1 =0.05
c2 =0.010
c3 =0.001
c4 =0.04
K = 0.80
x0 = 0
x_max = c2

########### Détermination de l'avancement à l'équilibre par dichotomie #############

# Initialisation
gauche = 0
droite = x_max
Q = 0    

# Dichotomie
while abs(Q-K) > 0.01:                # condition d'arrêt
    x = (gauche+droite)/2               # Nouveau milieu de l'intervalle possible
    Q = ((c3+x)*(c4+x))/((c2-x)*(c1-x)) # Nouvelle valeur du quotient de réaction    

    xx = np.linspace(gauche,droite)
    Qx=((c3+xx)*(c4+xx))/((c2-xx)*(c1-xx))
    
    plt.figure(1)
    plt.clf()
    plt.plot(xx,Qx)
    plt.plot(xx,K*np.ones(len(xx)))
    plt.xlabel('x (mol)')
    plt.ylabel('Q')
    plt.xlim(gauche,droite)
    plt.grid()
    plt.title('Quotient de réaction $Q$ en fonction de l\'avancement $x$')
    plt.show()
    
    if Q > K :
        droite = x
    else :
        gauche = x   
    
# Résultat 
x_eq = x
print("L'avancement à l'équilibre vaut", round(x_eq,6), "mol/L.")



