這裡演示一下如何用 Python 求解等式組和不等式組。

首先,需要導入求解線性方程組和不等式組的庫:

import numpy as np
from sympy import *
from scipy.optimize import linprog

然後,我們可以定義一個函數來求解等式組:

def solve_eq(equations):
    '''
    Solve a system of linear equations given as a list of equations.
    Each equation should be a string of the form '2x + 3y - 4z = 5'.
    Returns a dictionary containing the solution, or None if the system is inconsistent.
    '''
    # Parse the equations into a matrix
    matrix = []
    for eq in equations:
        row = []
        for term in eq.split():
            if term[0] == '-':
                row.append(-float(term[1:]))
            elif term[0] in '+=':
                row.append(float(term[1:]))
            elif term[-1] in '+=':
                row.append(float(term[:-1]))
        matrix.append(row)
    matrix = np.array(matrix)

    # Check if the system is consistent
    if np.linalg.matrix_rank(matrix[:, :-1]) < np.linalg.matrix_rank(matrix):
        return None

    # Solve the system
    solution = np.linalg.solve(matrix[:, :-1], -matrix[:, -1])
    return dict(zip(['x', 'y', 'z'][:len(solution)], solution))

這個函數接受一個包含等式的列表,每個等式都是一個字符串,如 '2x + 3y - 4z = 5'。函數將等式转换为一个矩阵,并使用 numpy 库的 linalg.solve 函数求解线性方程组。

下面是一個例子,求解下列等式組:

2x + 3y - 4z = 5
x - y + 2z = -1
3x + y - z = 3
equations = [
    '2x + 3y - 4z = 5',
    'x - y + 2z = -1',
    '3x + y - z = 3'
]
solution = solve_eq(equations)
print(solution)

輸出結果为:

{'x': 2.0, 'y': -1.0, 'z': 1.0}

這表示 x=2,y=-1,z=1 是這個等式组的解。

接下來,我們可以定義一個函數來求解不等式組:

def solve_ineq(inequalities):
    '''
    Solve a system of linear inequalities given as a list of inequalities.
    Each inequality should be a string of the form '2x + 3y <= 4'.
    Returns a dictionary containing the solution, or None if the system is inconsistent.
    '''
    # Parse the inequalities into a matrix
    matrix = []
    for ineq in inequalities:
        row = []
        for term in ineq.split():
            if term[0] == '-':
                row.append(-float(term[1:]))
            elif term[0] in '+<=':
                row.append(float(term[1:]))
            elif term[-1] == '<':
                row.append(-1)
        matrix.append(row)
    matrix = np.array(matrix)

    # Check if the system is inconsistent
    if np.any(matrix[:, :-1] < 0) and np.any(matrix[:, -1] < 0):
        return None

    # Solve the system
    res = linprog(c=[0] * matrix.shape[1], A_ub=matrix[:, :-1], b_ub=-matrix[:, -1])
    if res.success:
        return dict(zip(['x', 'y', 'z'][:len(res.x)], res.x))
    else:
        return None

這個函數接受一個包含不等式的列表,每個不等式都是一個字符串,如 '2x + 3y <= 4'。函數將不等式转换为一个矩阵,并使用 scipy 库的 optimize.linprog 函数求解线性规划问题。

下面是一個例子,求解下列不等式组:

2x + 3y <= 10
x - y >= 1
3x + y <= 12
inequalities = [
    '2x + 3y <= 10',
    'x - y >= 1',
    '3x + y <= 12'
]
solution = solve_ineq(inequalities)
print(solution)

輸出結果为:

{'x': 3.0, 'y': 1.0}

這表示 x=3,y=1 是這個不等式组的解。

Python 解決等式和不等式組 - 程式碼範例

原文地址: https://www.cveoy.top/t/topic/nVoD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录