当前位置: 首页 > news >正文

Python实例题:Python计算二元二次方程组

目录

Python实例题

题目

代码实现

实现原理

方程组定义:

数值求解方法:

可视化功能:

关键代码解析

1. 方程组定义

2. 求解函数

3. 2D 图像绘制

使用说明

运行程序:

示例输入输出:

注意事项

局限性:

精度问题:

性能考虑:

扩展建议:

Python实例题

题目

Python计算二元二次方程组

代码实现

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import root
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cmdef system_of_equations(vars, eq1_coeffs, eq2_coeffs):"""定义二元二次方程组参数:vars (tuple): (x, y) 变量eq1_coeffs (list): 第一个方程的系数 [a1, b1, c1, d1, e1, f1]eq2_coeffs (list): 第二个方程的系数 [a2, b2, c2, d2, e2, f2]返回:list: 方程组的值 [eq1_value, eq2_value]"""x, y = varsa1, b1, c1, d1, e1, f1 = eq1_coeffsa2, b2, c2, d2, e2, f2 = eq2_coeffs# 计算第一个方程的值eq1 = a1*x**2 + b1*x*y + c1*y**2 + d1*x + e1*y + f1# 计算第二个方程的值eq2 = a2*x**2 + b2*x*y + c2*y**2 + d2*x + e2*y + f2return [eq1, eq2]def solve_system(eq1_coeffs, eq2_coeffs, initial_guesses=None):"""求解二元二次方程组参数:eq1_coeffs (list): 第一个方程的系数 [a1, b1, c1, d1, e1, f1]eq2_coeffs (list): 第二个方程的系数 [a2, b2, c2, d2, e2, f2]initial_guesses (list): 初始猜测点列表,默认为None(使用默认猜测点)返回:list: 方程组的解 [(x1, y1), (x2, y2), ...]"""solutions = []# 如果没有提供初始猜测点,使用默认的猜测点if initial_guesses is None:# 在常见区域设置多个初始猜测点initial_guesses = [(0, 0), (1, 1), (-1, -1), (10, 10), (-10, -10),(10, -10), (-10, 10), (0, 10), (0, -10), (10, 0), (-10, 0)]# 对每个初始猜测点求解方程组for guess in initial_guesses:result = root(system_of_equations, guess, args=(eq1_coeffs, eq2_coeffs))# 检查求解是否成功if result.success:x, y = result.x# 检查解是否已经在列表中(考虑浮点数精度)is_duplicate = Falsefor sol in solutions:if np.allclose([x, y], sol, rtol=1e-5, atol=1e-6):is_duplicate = Truebreakif not is_duplicate:# 验证解是否同时满足两个方程eq1_val, eq2_val = system_of_equations([x, y], eq1_coeffs, eq2_coeffs)if abs(eq1_val) < 1e-6 and abs(eq2_val) < 1e-6:solutions.append((x, y))return solutionsdef plot_equations(eq1_coeffs, eq2_coeffs, solutions=None, x_range=(-10, 10), y_range=(-10, 10)):"""绘制二元二次方程组及其解参数:eq1_coeffs (list): 第一个方程的系数 [a1, b1, c1, d1, e1, f1]eq2_coeffs (list): 第二个方程的系数 [a2, b2, c2, d2, e2, f2]solutions (list): 方程组的解,默认为Nonex_range (tuple): x轴范围,默认为(-10, 10)y_range (tuple): y轴范围,默认为(-10, 10)"""# 创建网格x = np.linspace(x_range[0], x_range[1], 1000)y = np.linspace(y_range[0], y_range[1], 1000)X, Y = np.meshgrid(x, y)# 解析方程系数a1, b1, c1, d1, e1, f1 = eq1_coeffsa2, b2, c2, d2, e2, f2 = eq2_coeffs# 计算方程值Z1 = a1*X**2 + b1*X*Y + c1*Y**2 + d1*X + e1*Y + f1Z2 = a2*X**2 + b2*X*Y + c2*Y**2 + d2*X + e2*Y + f2# 创建图形plt.figure(figsize=(12, 10))# 绘制第一个方程的等高线(值为0的曲线)contour1 = plt.contour(X, Y, Z1, levels=[0], colors='blue', linewidths=2)plt.clabel(contour1, inline=True, fontsize=10)# 绘制第二个方程的等高线(值为0的曲线)contour2 = plt.contour(X, Y, Z2, levels=[0], colors='red', linewidths=2)plt.clabel(contour2, inline=True, fontsize=10)# 标记解点if solutions:for sol in solutions:plt.plot(sol[0], sol[1], 'go', markersize=10)plt.annotate(f'({sol[0]:.4f}, {sol[1]:.4f})', (sol[0], sol[1]), textcoords="offset points", xytext=(0,10), ha='center')# 添加标题和标签plt.title('二元二次方程组及其解', fontsize=16)plt.xlabel('x', fontsize=14)plt.ylabel('y', fontsize=14)plt.grid(True)# 添加图例plt.legend(['方程1', '方程2', '解'])# 显示图形plt.show()def plot_3d_equations(eq1_coeffs, eq2_coeffs, solutions=None, x_range=(-10, 10), y_range=(-10, 10)):"""绘制二元二次方程组的3D图像参数:eq1_coeffs (list): 第一个方程的系数 [a1, b1, c1, d1, e1, f1]eq2_coeffs (list): 第二个方程的系数 [a2, b2, c2, d2, e2, f2]solutions (list): 方程组的解,默认为Nonex_range (tuple): x轴范围,默认为(-10, 10)y_range (tuple): y轴范围,默认为(-10, 10)"""# 创建网格x = np.linspace(x_range[0], x_range[1], 100)y = np.linspace(y_range[0], y_range[1], 100)X, Y = np.meshgrid(x, y)# 解析方程系数a1, b1, c1, d1, e1, f1 = eq1_coeffsa2, b2, c2, d2, e2, f2 = eq2_coeffs# 计算方程值Z1 = a1*X**2 + b1*X*Y + c1*Y**2 + d1*X + e1*Y + f1Z2 = a2*X**2 + b2*X*Y + c2*Y**2 + d2*X + e2*Y + f2# 创建3D图形fig = plt.figure(figsize=(12, 10))ax = fig.add_subplot(111, projection='3d')# 绘制第一个方程的曲面surf1 = ax.plot_surface(X, Y, Z1, cmap=cm.Blues, alpha=0.5, linewidth=0, antialiased=True)# 绘制第二个方程的曲面surf2 = ax.plot_surface(X, Y, Z2, cmap=cm.Reds, alpha=0.5, linewidth=0, antialiased=True)# 绘制z=0平面ax.plot_surface(X, Y, np.zeros_like(X), alpha=0.1, color='gray')# 标记解点(如果有解)if solutions:for sol in solutions:x_sol, y_sol = solz_sol = 0  # 解点在z=0平面上ax.scatter(x_sol, y_sol, z_sol, color='green', s=100, marker='o')ax.text(x_sol, y_sol, z_sol, f'({x_sol:.4f}, {y_sol:.4f})', color='black', fontsize=12)# 添加标题和标签ax.set_title('二元二次方程组的3D图像', fontsize=16)ax.set_xlabel('x', fontsize=14)ax.set_ylabel('y', fontsize=14)ax.set_zlabel('方程值', fontsize=14)# 设置视角ax.view_init(elev=30, azim=45)# 添加图例fig.legend([surf1, surf2], ['方程1', '方程2'])# 显示图形plt.show()def main():"""主函数,处理用户输入并求解方程组"""try:print("="*50)print("        二元二次方程组求解器        ")print("="*50)print("\n请输入第一个方程的系数 (a1x² + b1xy + c1y² + d1x + e1y + f1 = 0):")a1 = float(input("  a1 = "))b1 = float(input("  b1 = "))c1 = float(input("  c1 = "))d1 = float(input("  d1 = "))e1 = float(input("  e1 = "))f1 = float(input("  f1 = "))print("\n请输入第二个方程的系数 (a2x² + b2xy + c2y² + d2x + e2y + f2 = 0):")a2 = float(input("  a2 = "))b2 = float(input("  b2 = "))c2 = float(input("  c2 = "))d2 = float(input("  d2 = "))e2 = float(input("  e2 = "))f2 = float(input("  f2 = "))# 构建系数列表eq1_coeffs = [a1, b1, c1, d1, e1, f1]eq2_coeffs = [a2, b2, c2, d2, e2, f2]# 求解方程组solutions = solve_system(eq1_coeffs, eq2_coeffs)# 输出结果print("\n" + "="*50)if solutions:print(f"方程组共有 {len(solutions)} 个实数解:")for i, sol in enumerate(solutions, 1):print(f"解 {i}: x = {sol[0]:.6f}, y = {sol[1]:.6f}")else:print("方程组没有找到实数解。")print("="*50)# 询问用户是否要绘制图像plot_option = input("\n是否绘制方程组图像?(y/n): ").lower()if plot_option == 'y':x_min = float(input("请输入x轴最小值: "))x_max = float(input("请输入x轴最大值: "))y_min = float(input("请输入y轴最小值: "))y_max = float(input("请输入y轴最大值: "))# 绘制2D图像plot_equations(eq1_coeffs, eq2_coeffs, solutions, (x_min, x_max), (y_min, y_max))# 询问是否绘制3D图像plot_3d_option = input("是否绘制3D图像?(y/n): ").lower()if plot_3d_option == 'y':plot_3d_equations(eq1_coeffs, eq2_coeffs, solutions, (x_min, x_max), (y_min, y_max))except ValueError as ve:print(f"输入错误: {ve}")except Exception as e:print(f"发生错误: {e}")if __name__ == "__main__":main()    

实现原理

这个二元二次方程组求解器基于以下技术实现:

  • 方程组定义

    • 支持标准形式的二元二次方程组
    • 使用系数列表表示每个方程
  • 数值求解方法

    • 使用 scipy.optimize.root 函数求解非线性方程组
    • 设置多个初始猜测点以寻找所有可能的解
    • 使用容差检查解的有效性和唯一性
  • 可视化功能

    • 2D 图像展示两个方程的曲线及其交点
    • 3D 图像展示方程曲面与 z=0 平面的交线
    • 标记并显示所有实数解的坐标

关键代码解析

1. 方程组定义

def system_of_equations(vars, eq1_coeffs, eq2_coeffs):x, y = varsa1, b1, c1, d1, e1, f1 = eq1_coeffsa2, b2, c2, d2, e2, f2 = eq2_coeffseq1 = a1*x**2 + b1*x*y + c1*y**2 + d1*x + e1*y + f1eq2 = a2*x**2 + b2*x*y + c2*y**2 + d2*x + e2*y + f2return [eq1, eq2]

2. 求解函数

def solve_system(eq1_coeffs, eq2_coeffs, initial_guesses=None):solutions = []if initial_guesses is None:initial_guesses = [(0, 0), (1, 1), (-1, -1), (10, 10), (-10, -10),(10, -10), (-10, 10), (0, 10), (0, -10), (10, 0), (-10, 0)]for guess in initial_guesses:result = root(system_of_equations, guess, args=(eq1_coeffs, eq2_coeffs))if result.success:x, y = result.x# 检查解是否已存在并验证解的有效性is_duplicate = Falsefor sol in solutions:if np.allclose([x, y], sol, rtol=1e-5, atol=1e-6):is_duplicate = Truebreakif not is_duplicate:eq1_val, eq2_val = system_of_equations([x, y], eq1_coeffs, eq2_coeffs)if abs(eq1_val) < 1e-6 and abs(eq2_val) < 1e-6:solutions.append((x, y))return solutions

3. 2D 图像绘制

def plot_equations(eq1_coeffs, eq2_coeffs, solutions=None, x_range=(-10, 10), y_range=(-10, 10)):x = np.linspace(x_range[0], x_range[1], 1000)y = np.linspace(y_range[0], y_range[1], 1000)X, Y = np.meshgrid(x, y)a1, b1, c1, d1, e1, f1 = eq1_coeffsa2, b2, c2, d2, e2, f2 = eq2_coeffsZ1 = a1*X**2 + b1*X*Y + c1*Y**2 + d1*X + e1*Y + f1Z2 = a2*X**2 + b2*X*Y + c2*Y**2 + d2*X + e2*Y + f2plt.figure(figsize=(12, 10))# 绘制等高线(值为0的曲线)contour1 = plt.contour(X, Y, Z1, levels=[0], colors='blue', linewidths=2)contour2 = plt.contour(X, Y, Z2, levels=[0], colors='red', linewidths=2)# 标记解点if solutions:for sol in solutions:plt.plot(sol[0], sol[1], 'go', markersize=10)plt.annotate(f'({sol[0]:.4f}, {sol[1]:.4f})', (sol[0], sol[1]), textcoords="offset points", xytext=(0,10), ha='center')plt.title('二元二次方程组及其解', fontsize=16)plt.xlabel('x', fontsize=14)plt.ylabel('y', fontsize=14)plt.grid(True)plt.legend(['方程1', '方程2', '解'])plt.show()

使用说明

  • 运行程序

python system_quadratic_solver.py
  • 输入方程系数: 按照提示依次输入两个方程的系数 \(a, b, c, d, e, f\)。

  • 查看结果: 程序会输出方程组的所有实数解,并可以选择绘制 2D 和 3D 图像以直观展示。

示例输入输出

请输入第一个方程的系数 (a1x² + b1xy + c1y² + d1x + e1y + f1 = 0):a1 = 1b1 = 0c1 = 1d1 = 0e1 = 0f1 = -4请输入第二个方程的系数 (a2x² + b2xy + c2y² + d2x + e2y + f2 = 0):a2 = 1b2 = 0c2 = -1d2 = 0e2 = 0f2 = 0==================================================
方程组共有 4 个实数解:
解 1: x = 1.414214, y = 1.414214
解 2: x = 1.414214, y = -1.414214
解 3: x = -1.414214, y = 1.414214
解 4: x = -1.414214, y = -1.414214
==================================================

注意事项

  • 局限性

    • 此程序只能找到实数解,无法找到复数解
    • 对于某些特殊方程组,可能需要调整初始猜测点
    • 数值方法可能无法找到所有解,尤其是当解的数量很多时
  • 精度问题

    • 浮点数精度可能导致微小误差
    • 解的验证使用容差(1e-6),可根据需要调整
  • 性能考虑

    • 绘制高分辨率图像可能需要较长时间
    • 复杂方程组可能需要更多的初始猜测点
  • 扩展建议

    • 添加符号解法支持(使用 SymPy 库)
    • 实现解的稳定性分析
    • 增加交互式界面调整参数和查看结果
http://www.xdnf.cn/news/889903.html

相关文章:

  • Life:Internship finding
  • RMSE可以融合均值与标准差
  • 核货宝订货平台源码:构建高效智能订货系统,驱动企业数字化转型
  • Nature Methods | OmiCLIP:整合组织病理学与空间转录组学的AI模型
  • win32相关(远程线程和远程线程注入)
  • React 第五十四节 Router中useRevalidator的使用详解及案例分析
  • Next打包导出静态文件(纯前端),不要服务器端(node), 隐藏左下角调试模式
  • Conda 基本使用命令大全
  • 数据库优化实战分享技术文章大纲
  • Qt 开发中的父类与父对象的区别和父对象传递:如何选择 `QWidget` 或 `QObject`?
  • Palo Alto Networks Expedition存在命令注入漏洞(CVE-2025-0107)
  • dvwa11——XSS(Reflected)
  • 视频爬虫的Python库
  • 鸿蒙Next开发真机调试签名申请流程
  • Qt/C++学习系列之QGroupBox控件的简单使用
  • 【TinyWebServer】线程同步封装
  • Raw Denoising 论文,以及如何制作noisy-clean图像对
  • AI问答-vue3+ts+vite:http://www.abc.com:3022/m-abc-pc/#/snow 这样的项目 在服务器怎么部署
  • 亲测解决self.transform is not exist
  • vscode里如何用git
  • TIA博途中的程序导出为PDF格式的具体方法示例
  • [zynq] Zynq Linux 环境下 AXI BRAM 控制器驱动方法详解(代码示例)
  • MYSQL(三)--服务器启动参数与配置
  • 群晖NAS如何在虚拟机创建飞牛NAS
  • ABP VNext 在 Kubernetes 中的零停机蓝绿发布
  • Abaqus载荷与边界条件(Load BC)
  • 将 Jupyter Notebook 的默认存储路径从 C 盘迁移到 D 盘,可以通过以下步骤实现:
  • 【教学类】20250605立体纸盘(3边形-22边形,角度5、10……40,45)
  • TikTok养号指南:从0到1打造防限流账号的实战策略
  • 【西门子杯工业嵌入式-1-基本环境与空白模板】