# 円を描画
"""課題1，周期補間"""

import matplotlib.pyplot as plt # 描画ライブラリ
import math

class A:
    def __init__(self):
        self.ly = [0.1, 0.2, -0.1 , 0.2]
        self.h = 0.1
        self.N = len(self.ly)
    def f(self, x):
        i1 = int(x/self.h) 
        if x < 0:
            i1 = i1 -1
        i2 = i1 + 1 
        x1 = i1*self.h
        x2 = i2*self.h
        s = (x - x1)/self.h
        t = 1 - s
        i1h = i1%self.N
        i2h = i2%self.N
        i1p = (i1h + self.N)%self.N
        i2p = (i2h + self.N)%self.N
        y = self.ly[i2p]*s + self.ly[i1p]*t
        return y
a=A()
mlx=[]
mly=[]

N = 256
T = 2.4
dx = 1.0/(N-1)*T 
x = -1.1
for j in range(N):
    y=a.f(x)
    mlx.append(x)
    mly.append(y)
    x=x+dx

fig=plt.figure()
ax=fig.add_subplot()
ax.scatter(mlx, mly, marker='+',s=1, color='red')
ax.set_aspect(1)
plt.savefig("f1.svg")
plt.close()

'''課題2: sin, cos の内挿による計算関数のクラス化'''
import matplotlib.pyplot as plt # 描画ライブラリ
import math

class myMath:
    def __init__(self, N, M):
        self.ly = []
        self.lx = []

        x = 1
        y = 0
        self.π = 3.14159265357989 
        h = 2*self.π/(N*M) # 幅の計算に気をつける．2*self.π/(N*M) ではない．
        for i in range(N*M): 
            if i%M == 0:
                self.lx.append(x)
                self.ly.append(y)
            xn = x - y*h
            yn = y + x*h
            x = xn
            y = yn
        self.h = 2*self.π/N
        self.N = N

    def sin(self, θ):
        h = self.h
        N = self.N
        ly = self.ly
        a = int(θ/h)
        if θ < 0:
            a -= 1
        r1 = (θ - a*h)/h
        r2 = 1 - r1
        i1 = (a % N + N)%N
        i2 = (i1 + 1) % N
        s = ly[i1]*r2 + ly[i2]*r1
        return s
    def cos(self, θ):
        h = self.h
        N = self.N
        lx = self.lx
        a = int(θ/h)
        if θ < 0:
            a -= 1
        r1 = (θ - a*h)/h
        r2 = 1 - r1
        i1 = (a % N + N)%N
        i2 = (i1 + 1) % N
        s = lx[i1]*r2 + lx[i2]*r1
        return s

## ここから「ここまで」まで改変しない ###
m = myMath(32, 256)

lt = []
ls = []
lc = []
t = -1
π = math.pi
while t < 1:
    lt.append(t)
    ls.append(m.sin(t*4*π))
    lc.append(m.cos(t*4*π))
    t += 0.001
    

fig = plt.figure()
ax = fig.add_subplot()
ax.scatter(lt, ls, s=0.2) # 凡例を付けて描画
ax.scatter(lt, lc, s=0.2) # 凡例を付けて描画
# ax.set_xlim(-1, 5)
ax.set_aspect(1)# axis("equal") # アスペクト比を1に設定
ax.set_xlabel("x")
ax.set_ylabel("y")
## 「ここまで」 ###

# plt.show() # 画面へ描画
plt.savefig("r.svg")
plt.close()