python - 使用 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)
但我希望程序询问系数,这样我就不必为每个方程编辑它。我确信这是可能的,但我已经搜索了好几天,但什么也没找到。我想知道你能否给我一些关于如何实现它的提示。
解决方案
我找到了怎么做。这是代码:
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。
推荐阅读
- create-react-app - 如何将 Jest intellisense 与 create-react-app 和 VScode 一起使用?
- react-native - 如何为不同用户创建单独的导航抽屉:React 导航 v5
- python-2.7 - 皮林特和蟒蛇
运行关于包的相对导入的冲突('没有命名的模块 ' 如果我按照 pylint 方式进行操作,则会出错) - r - 如何使用 R 中其他列的值格式化字符串
- javascript - 为什么我的 D3.csv() 方法返回“未定义”
- bash - 我如何将文件名存储为shell脚本中的变量
- r - 缺失单元的自动插值
- spring - Spring mvc 找不到 post 方法的表示
- r - 根据R中循环内两个数据帧中的匹配值进行过滤
- python - 中断 GNU Parallel 后如何将 KeyboardInterrupt 提升到 Python 脚本?