import numpy as np
import os
import csv
base = os.path.abspath(os.path.dirname(__file__)) # 当前路径
file_name = "/ordinates_data.csv"
file_path = base + file_name
radius = 100 # 设置圆的半径
step = 0.05 # 步长为0.05
start = 0
end = 100 + step
X_LIST = np.arange(start,end, step) # [0, 100] 每隔0.05取1个值
LENGTH = len(X_LIST) # 序列x的长度
pow_value = np.ones(LENGTH) * 2 # 有LENGTH个元素值为2的array型的列表
Y_LIST = np.sqrt(radius**2 - np.power((X_LIST-radius),pow_value)) # 圆的方程求解
# 由于有些太小的值,计算机可能会将其赋值为Nan型,因此要将值为Nan的元素置为0
Y_LIST[np.isnan(Y_LIST)] = 0
X_LIST = np.round(X_LIST, 5) # np.round()函数第2个参数值为小数点后面保留的位数
Y_LIST = np.round(Y_LIST, 5)
# 将数据写入file_path文件中
with open(file_path,'w+') as csvfile:
header = ['x', 'y']
writer = csv.DictWriter(csvfile, fieldnames=header)
writer.writeheader()
for idx in range(LENGTH):
x = X_LIST[idx]
y = Y_LIST[idx]
writer.writerow({'x':x, 'y':y})
# 因为输入的值不一定落在X_LIST序列里,因此需要将其转化为离其最近的x坐标点
def find_close_data(X_LIST, e):
LENGTH = len(X_LIST) # 序列x的长度
e_list = np.ones(LENGTH) * e # 有LENGTH个元素值为e的array型的列表
distance = list(np.abs(e_list - X_LIST))
index = distance.index(min(distance))
y = Y_LIST[index]
return y
while True:
input_x = input("Please enter the value of the x coordinate:")
input_x = float(input_x)
data_y = find_close_data(X_LIST, input_x)
# 当输入大于100的值,程序退出
if input_x > 100:
break
print(data_y)