import matplotlib.pyplot as plt
import numpy as np

F1 = [0 for _ in range(1001)]
G1 = [0 for _ in range(1001)]
Gx = [0 for _ in range(1001)]
gx = []


def F(n):
    F1[n] = 1
    for k in range(n - 1, 0, -1):
        sum = 0
        for i in range(k, n):
            if i <= n / 2:
                sum += 1 / i * F1[np.math.ceil(i * n / (n - i))]
            else:
                sum += 1 / i
        F1[k] = 1 - sum


def G(n):
    G1[0] = 0
    Gx[0] = 0
    for k in range(1, n + 1):
        sum = 0
        for i in range(k, 2 * k + 1):
            if i >= n - k:
                sum += 1 / i
            else:
                sum += 1 / i * F1[np.math.ceil(k * n / (n - i))]
        G1[k] = sum
        Gx[k] = min(F1[k] + G1[k], 1)
        gx.append(1000 * (Gx[k] - Gx[k - 1]))


F(1000)
G(1000)

print(max(gx))
print(gx.index(max(gx)))

x = np.linspace(0, 0.5, 499)
y = gx[0:499]

# Figure 并指定大小
plt.figure(num=3, figsize=(8, 5))
plt.plot(x, y, linewidth=1.0)

# 设置 x，y 轴的范围以及 label 标注
plt.xlim(0, 1)
plt.ylim(0, 7.5)

# 设置坐标轴刻度线
new_ticks = np.linspace(0, 1, 11)
plt.xticks(new_ticks)


# 设置坐标轴 gca() 获取坐标轴信息
ax = plt.gca()

# 移动坐标轴
# 将 bottom 即是 x 坐标轴设置到 y=0 的位置。
ax.xaxis.set_ticks_position("bottom")
ax.spines["bottom"].set_position(("data", 0))

# 将 left 即是 y 坐标轴设置到 x=0 的位置。
ax.yaxis.set_ticks_position("left")
ax.spines["left"].set_position(("data", 0))

# 设置标签
ax.set_title("g(x)=G'(x)", fontsize=14)
ax.set_xlabel("x", fontsize=14)
ax.set_ylabel("g(x)", fontsize=14)

# 显示图像
plt.show()
