首页 > 解决方案 > 使用 Python 为线性方程组求解器创建数组

问题描述

我是这个网站的新手,也是 Python 的新手。我记得我在学校的时候,我用 BASIC 写了一个程序(那是八十年代),用矩阵求解线性方程组。

我想在 Python 中做同样的事情,我发现它可以用这样的代码来完成:

import numpy as np

a = np.array([[8, 3, -2], [-4, 7, 5], [3, 4, -12]])
b = np.array([9, 15, 35])

x = np.linalg.solve(a, b)

print (x)

但我希望程序询问系数,这样我就不必为每个方程编辑它。我确信这是可能的,但我已经搜索了好几天,但什么也没找到。我想知道你能否给我一些关于如何实现它的提示。

标签: pythonarrayslinear-equation

解决方案


我找到了怎么做。这是代码:

import numpy as np

print (" Résolution de systèmes de n équations à n inconnues :")

# Saisie du nombre d’inconnues
print ("\n")
m = int(input(" Nombre d’inconnues ? "))
n = m

mat_a = []
mat_b = []

# Saisie des coefficients - matrice A
print ("\n")
print (" Saisie des coefficients – Matrice [A] :")
for i in range (0,n):
    mat_a.append([])
for i in range (0,m):
    for j in range (0,n):
        mat_a[i].append(j)
        mat_a[i][j]=0
for i in range (0,m):
    for j in range (0,n):
        print (" Coefficient [", i+1,", ",j+1, "] ?", end = " ")
        mat_a[i][j] = eval(input())

# Saisie des coefficients - matrice B
m = 1
print ("\n")
print (" Saisie des coefficients – Matrice [B] :")
for i in range (0,n):
    mat_b.append([])
for i in range (0,n):
    for j in range (0,m):
        mat_b[i].append(j)
        mat_b[i][j]=0
for i in range (0,n):
    for j in range (0,m):
        print (" Coefficient [", i+1,", ",j+1, "] ?", end = " ")
        mat_b[i][j] = eval(input())

# Création des matrices
a = np.array ([mat_a])
b = np.array ([mat_b])

# Résolution du système d’équations       
x = np.linalg.solve(a, b)

# Affichage des solutions
print ("\n")
print (" L’équation admet", n, "solutions. S = {", x, "}.")

# Sortie du programme
print ("\n")
input (" Appuyer sur <Entrée> pour quitter…")

youtube 上的视频帮助了我:如何在 Python 中制作 2D 列表或矩阵并接受用户的输入

经过一些更改,我设法为我的小程序编写了好的代码。

如果您想尝试一下,请使用以下系统,例如:

4x + 2y = -1
3x - y = 2

这两个解是S = {0,3 ; -1,1}

:)

W。


推荐阅读