查看原文
其他

G2313班殷浩然、肖垚的Python程序作品《n 次根式近似值计算器》

殷浩然、肖垚 信息科技时代
2024-08-23

程序作品源码:

# 导入库import tkinter as tkfrom tkinter import messageboxfrom fractions import Fractionimport os
# 调整小数点def adjust(num): adjust.times_adjustment = 0 if num == 0: adjust.times_adjustment = 0 elif num < 1: while num < 1: num *= 10 adjust.times_adjustment += 1 elif num > 1: while num > 1: num /= 10 adjust.times_adjustment -= 1 else: adjust.times_adjustment = -1 return adjust.times_adjustment
# 程序主体def calculate(): value_n = entry_n.get() value_m = entry_m.get() if not value_n or not value_m: messagebox.showinfo("提示", "请输入正确的数值!") else: x = float(1) n = float(value_n) m = float(value_m) times_iteration = int(entry_iteration.get())
# 使用公式进行迭代计算 for i in range(1, (times_iteration + 1)): x = ((x * (n - 1)) / n) + (m / (n * x**(n - 1)))
# 使用运算符计算精确值 X = m**(1 / n) # 计算分数形式 x_fraction = Fraction(x).limit_denominator() numerator = x_fraction.numerator denominator = x_fraction.denominator
# 输出结果 result_text.set(f"公式计算结果:\n小数形式:x = {x}\n分数形式:x = {numerator}/{denominator}\n\n计算器计算结果: x = {X}\n\n误差约为:{abs(X - x)}")
# 迭代次数对误差的影响 key = 0 for i in range(1, (times_iteration + 1)): xX = 1 for I in range(1, (i + 1)): xX = ((xX * (n - 1)) / n) + (m / (n * xX**(n - 1))) if i == times_iteration: continue elif adjust(abs(X - xX)) == key: continue key = adjust(abs(X - xX)) if abs(X - xX) == 0: iteration_result_text.set(f"\n迭代次数为: {i} 时 误差几乎为 0.0\n结束迭代") break else: iteration_result_text.set(f"\n迭代次数为: {i} 时 误差减小到后{abs(X - xX)}位\n误差约为 {float(abs(X - xX))}") pass
# 创建主窗口root = tk.Tk()root.title("n 次根式近似值计算器")
# 创建输入框和标签label_n = tk.Label(root, text="请输入要开方的指数(阿拉伯数字):", anchor="w")label_n.grid(row=0, column=0, padx=10, pady=5, sticky="w")entry_n = tk.Entry(root)entry_n.grid(row=0, column=1, padx=10, pady=5, sticky="w")
label_m = tk.Label(root, text="请输入要开方的数字 x(x 为正整数):")label_m.grid(row=1, column=0, padx=10, pady=5, sticky="w")entry_m = tk.Entry(root)entry_m.grid(row=1, column=1, padx=10, pady=5, sticky="w")
label_iteration = tk.Label(root, text="请输入要迭代的次数:")label_iteration.grid(row=2, column=0, padx=10, pady=5, sticky="w")entry_iteration = tk.Entry(root)entry_iteration.grid(row=2, column=1, padx=10, pady=5, sticky="w")
# 创建计算按钮calculate_button = tk.Button(root, text="计算", command=calculate, width=30)calculate_button.grid(row=3, column=0, columnspan=2, padx=10, pady=5)
# 创建结果展示区域result_text = tk.StringVar()result_label = tk.Label(root, textvariable=result_text)result_label.grid(row=4, column=0, columnspan=2, padx=10, pady=5)
iteration_result_text = tk.StringVar()iteration_result_label = tk.Label(root, textvariable=iteration_result_text)iteration_result_label.grid(row=5, column=0, columnspan=2, padx=10, pady=5)
# 运行主循环root.mainloop()

    程序运行结果:

    《2024年校科技节之中小学信息素养实践活动作品评奖结果公示》获奖作品等级不高,不是作品不好,而是获奖比例有限制。

继续滑动看下一个
信息科技时代
向上滑动看下一个

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存