Эх сурвалжийг харах

添加test_ai测试代码

alex 6 сар өмнө
parent
commit
ad84308fc4
3 өөрчлөгдсөн 240 нэмэгдсэн , 0 устгасан
  1. 121 0
      test_ai.py
  2. 24 0
      test_gym.py
  3. 95 0
      test_web_auto.py

+ 121 - 0
test_ai.py

@@ -0,0 +1,121 @@
+import math
+import tkinter as tk
+from tkinter import messagebox, ttk
+from decimal import Decimal, getcontext
+import threading
+
+# 定义 Chudnovsky 算法计算圆周率的函数
+def compute_pi_chudnovsky(iterations, progress_callback):
+    # 设置 Decimal 精度,确保足够的有效数字
+    getcontext().prec = 250  # 设置更高的精度,确保中间计算的准确性
+
+    # 初始化常量
+    C = Decimal(426880) * Decimal(10005).sqrt()
+    M = Decimal(1)
+    L = Decimal(13591409)
+    X = Decimal(-262537412640768000)  # 初始 X
+    K = Decimal(6)
+    S = Decimal(L)
+
+    total_iterations = iterations
+    for i in range(1, total_iterations + 1):  # 从 1 开始迭代
+        if i % 10 == 0:
+            progress_callback((i / total_iterations) * 100)
+
+        # 计算 M 和 L
+        M = (K**3 - 16 * K) * M // Decimal(i**3)
+        L += Decimal(545140134)
+
+        # 计算 S
+        try:
+            S += M * L / X
+        except ZeroDivisionError as e:
+            raise ValueError(f"除零错误在迭代次数: {i}, X: {X}, M: {M}, L: {L}") from e
+        except Exception as e:
+            raise ValueError(f"其他错误在迭代次数: {i}, X: {X}, M: {M}, L: {L}, S: {S}") from e
+
+        # 更新 X 和 K
+        X *= Decimal(-262537412640768000)
+        K += Decimal(12)
+
+    pi = C / S
+    return +pi  # 返回正数值
+
+# 定义工作线程函数,用于在后台计算圆周率
+def worker(iterations, progress_callback, result_callback):
+    try:
+        pi_computed = compute_pi_chudnovsky(iterations, progress_callback)
+        result_callback(pi_computed)
+    except Exception as e:
+        result_callback(None, str(e))
+
+# 定义计算按钮点击事件处理函数
+def on_calculate():
+    try:
+        iterations = int(entry_iterations.get())
+        if iterations < 1:
+            raise ValueError("迭代次数必须大于0")
+
+        # 创建进度窗口
+        progress_window = tk.Toplevel(root)
+        progress_window.title("计算进度")
+
+        # 初始化进度条变量
+        progress_var = tk.DoubleVar()
+        # 创建进度条控件
+        progress = ttk.Progressbar(progress_window, variable=progress_var, maximum=100)
+        progress.pack(pady=20, padx=20, fill='x')
+        # 创建进度标签控件
+        progress_label = tk.Label(progress_window, text="0%")
+        progress_label.pack(pady=10)
+
+        def progress_callback(progress):
+            progress_var.set(progress)
+            progress_label.config(text=f"{int(progress)}%")
+            progress_window.update_idletasks()
+
+        # 定义结果回调函数
+        def result_callback(pi_computed, error=None):
+            progress_window.destroy()
+            if error:
+                messagebox.showerror("错误", error)
+            else:
+                # 获取数学库中的 π 值(这里使用 Decimal 包装)
+                pi_math = Decimal(str(math.pi))
+
+                # 计算误差
+                difference = abs(pi_computed - pi_math)
+
+                # 格式化显示计算结果和数学库中的 π 值,并用科学计数法显示误差
+                pi_computed_str = f"{pi_computed:.200f}".rstrip('0').rstrip('.')
+                pi_math_str = f"{pi_math:.200f}".rstrip('0').rstrip('.')
+                difference_str = f"{difference:.20e}"
+
+                message = (f"计算得到的π: {pi_computed_str}\n"
+                           f"数学库中的π: {pi_math_str}\n"
+                           f"差异: {difference_str}")
+                messagebox.showinfo("结果", message)
+
+        # 创建并启动线程进行计算
+        thread = threading.Thread(target=worker, args=(iterations, progress_callback, result_callback))
+        thread.start()
+    except ValueError as e:
+        messagebox.showerror("错误", str(e))
+
+# 创建主窗口
+root = tk.Tk()
+root.title("计算圆周率")
+
+# 创建标签和输入框
+label_iterations = tk.Label(root, text="迭代次数:")
+label_iterations.grid(row=0, column=0, padx=10, pady=10)
+
+entry_iterations = tk.Entry(root)
+entry_iterations.grid(row=0, column=1, padx=10, pady=10)
+
+# 创建计算按钮
+button_calculate = tk.Button(root, text="计算", command=on_calculate)
+button_calculate.grid(row=1, column=0, columnspan=2, pady=10)
+
+# 运行主循环
+root.mainloop()

+ 24 - 0
test_gym.py

@@ -0,0 +1,24 @@
+import gym
+import time
+
+# 生成环境
+env = gym.make('CartPole-v1', render_mode='human')
+# 环境初始化
+state = env.reset(seed=1)
+# 循环交互
+
+while True:
+    # 渲染画面
+    # env.render()
+    # 从动作空间随机获取一个动作
+    action = env.action_space.sample()
+    # agent与环境进行一步交互
+    state, reward, terminated, truncated, info = env.step(action)
+    print('state = {0}; reward = {1}'.format(state, reward))
+    # 判断当前episode 是否完成
+    if terminated:
+        print('terminated')
+        break
+    time.sleep(0.1)
+# 环境结束
+# env.close()

+ 95 - 0
test_web_auto.py

@@ -0,0 +1,95 @@
+#
+from selenium import webdriver
+from selenium.webdriver.chrome.service import Service
+from selenium.webdriver.chrome.options import Options
+from selenium.webdriver.common.by import By
+from selenium.webdriver.support.ui import WebDriverWait
+from selenium.webdriver.support import expected_conditions as EC
+import time
+
+
+def traverse_iframes(driver, iframe_list=None):
+    """
+    递归遍历网页中的所有iframe
+
+    :param driver: Selenium的WebDriver实例
+    :param iframe_list: 用于存储已遍历的iframe元素的列表,默认为None
+    :return: 包含所有iframe元素的列表
+    """
+    if iframe_list is None:
+        iframe_list = []
+    # 查找当前页面下所有的iframe元素
+    iframes = driver.find_elements("tag name", "iframe")
+    for iframe in iframes:
+        iframe_list.append(iframe)
+        # 切换到当前iframe
+        driver.switch_to.frame(iframe)
+        print(iframe.id)
+        e = driver.find_elements(By.ID, 'switcher_plogin')
+        if e is None:
+            # e[0].click()
+            print(f'e={e}')
+        # 递归调用,继续查找当前iframe内部的iframe元素
+        traverse_iframes(driver, iframe_list)
+        # 切换回父级(上一层),这样才能继续查找同一层级的其他iframe
+        driver.switch_to.parent_frame()
+    return iframe_list
+
+# # 配置 ChromeDriver 路径,替换为你的 ChromeDriver 路径,你也可以将chromedriver拖入文件根目录,使用'./chromedriver.exe'路径。
+# chrome_driver_path = 'D:/JIAL/JIALConfig/chromedriver/chromedriver.exe'  # 替换为你的 ChromeDriver 路径
+#
+# # 初始化 ChromeDriver Service
+# service = Service(chrome_driver_path)
+# # 打开浏览器时的相关配置,可以根据需求进行打开和关闭
+# options = Options()
+# options.add_argument("--start-maximized")  # 启动时最大化窗口
+# # options.add_argument("--disable-blink-features=AutomationControlled")  # 使浏览器不显示自动化控制的信息
+# # options.add_argument("--disable-gpu")  # 禁用GPU硬件加速
+# # options.add_argument("--disable-infobars")  # 隐藏信息栏
+# # options.add_argument("--disable-extensions")  # 禁用所有扩展程序
+# # options.add_argument("--disable-popup-blocking")  # 禁用弹出窗口拦截
+# # options.add_argument("--incognito")  # 启动无痕模式
+# # options.add_argument("--no-sandbox")  # 关闭沙盒模式(提高性能)
+# # options.add_argument("--disable-dev-shm-usage")  # 使用/dev/shm分区以避免共享内存问题
+# # options.add_argument("--remote-debugging-port=9222")  # 启用远程调试端口
+# # 初始化 WebDriver,并传入 ChromeDriver Service
+driver = webdriver.Chrome()
+
+# 打开百度搜索首页
+driver.get("https://mail.qq.com/")
+#
+# 打印页面标题
+print(driver.title)
+# 延时5秒钟,也就是浏览器打开5秒钟,避免闪退
+time.sleep(1)
+
+# def find_all_iframes(idriver):
+#     iframes = idriver.find_elements('tag name','iframe')
+#     for index, iframe in enumerate(iframes):
+#         # Your sweet business logic applied to iframe goes here.
+#         # print(iframe.id)
+#         driver.switch_to.frame(index)
+#         e = driver.find_elements(By.ID, 'switcher_plogin')
+#         print(e)
+#         find_all_iframes(idriver)
+#         driver.switch_to.parent_frame()
+
+# find_all_iframes(driver)
+all_iframes  = traverse_iframes(driver)
+# print(all_iframes)
+# print(driver.page_source)
+# driver.find_element_by_id('j_username').send_keys('***')
+# e=driver.find_element('class name','switcher_plogin')
+# driver.switch_to.frame('ptlogin_iframe')
+
+# e=driver.find_elements('tag name','iframe')
+# # e=driver.find_element(By.ID,'switcher_plogin')
+# print(e)
+#
+# driver.switch_to.frame(1)
+# e=driver.find_elements('tag name','iframe')
+# # e=driver.find_element(By.ID,'switcher_plogin')
+# print(e)
+time.sleep(1)
+# 关闭 WebDriver
+driver.quit()