import numpy as np
import matplotlib.pyplot as plt

print("\n\n1.1")
def estDansLaBoule(x, r):
    """
    x=(x1,x2,x3) est une liste ou vecteur
    r est le rayon de la boule centre a l'origine
    """
    x1, x2, x3 = x
    tmp = x1**2 + x2**2 + x3**2
    return r**2 >= tmp

tests = [[[-1/2, -1/4, 1/5], 0.5937], [[0.2, 0.2, 0.1], 0.3], [[2, 2, 1], 3]]
for t in tests:
    x, r = t
    print(f"pour {x} et {r} on obtient {estDansLaBoule(x, r)}")



print("\n\n1.2")
def melanger(x, y):
    res = ''
    n = min(len(x), len(y))
    for k in range(n):
        res += x[k] + y[k]
    if len(x) > len(y):
        res += x[n:]  
    elif len(x) < len(y):
        res += y[n:]
    return res


tests = [('abcd', 'xy'), ('a', 'bc'), ('ab', 'c'), ('abcd', 'd ef')]
for t in tests:
    x, y = t
    print(f"pour x = {x} et y = {y}, on obtient {melanger(x, y)}")


    
print("\n\n1.3")
def symEtAntisym(M):
    """
    M est une matrice carree.
    """
    S = 0.5*(M + M.T)
    A = 0.5*(M - M.T)
    
    n, m = np.shape(M)
    P = np.eye(n)
    for k in range(n):
        P = P.dot(S)
    return S, A, P


M = np.array([[1, 2, 3], [-1, -2, -3], [0, -1, 1]])
print(f"M = {M}")
S, A, P = symEtAntisym(M)
print(f"S = {S} \net \nA = {A}")
print(f"et la puissance de S \n{P}")



print("\n\n1.4")
a = np.sqrt(2)
theta = np.linspace(0, 2*np.pi, 200)
x_cercle = 2*np.cos(theta)
y_cercle = 2*np.sin(theta)

plt.figure()
plt.title("un cercle rayon 2 et deux diametres a 45 degres")
plt.axis("equal")
# plt.grid(True)
plt.plot(x_cercle, y_cercle, color='k') 
plt.plot([-2, 2], [0, 0], color='b', linewidth=.5)  # un diametre horizontal
plt.plot([-a, a], [-a, a], color='r', linewidth=.5)  # un diametre a 45
plt.show()



print("\n\n\n2.1")
def sommePartielle(n):
    S = 0
    for k in range(n + 1):
        S += (-1/3)**k / (2*k + 1)
    return S


print("\n\n2.2")
def sommesPartielles(n):
    L = []
    S = 0
    for k in range(n + 1):
        S += (-1/3)**k / (2*k + 1)
        L.append(S)
    return L

n = 10
print(f"pour n = {n} on a les sommes partielles \n{sommesPartielles(n)}")


print("\n\n2.3 et 2.4")
n = 25
stilde = 0.9068995
x = list(range(n + 1))
y = sommesPartielles(n)
plt.figure()
plt.title(f"Premieres {n} sommes partielles")
# plt.axis("equal")
plt.grid(True)
plt.plot(x, y, color='b', lw=2, marker='o', ms='5')
plt.plot([0, n], [stilde, stilde], color='r', lw=.5)
plt.show()


print("\n\n2.5")
def terme(n):
    return 1/3**n / (2*n + 1)


def calculApproche(d):
    e = 10**(-d)
    N = 1
    while terme(N + 1) > e:
        N = N + 1
    return sommePartielle(N), N

print(calculApproche(4))
print(calculApproche(7))
print(calculApproche(10)) 
print(calculApproche(11)) 
