gpt4 book ai didi

python - 求解一对线性方程时的断言错误

转载 作者:行者123 更新时间:2023-12-05 07:10:54 25 4
gpt4 key购买 nike

def lin_eqn(a,b):
'''
Solve the system of linear equations
of the form ax = b
Eg.
x + 2*y = 8
3*x + 4*y = 18

Given inputs a and b represent coefficients and constant of linear equation respectively

coefficients:
a = np.array([[1, 2], [3, 4]])

constants:
b = np.array([8, 18])

Desired Output: [2,3]
'''
# YOUR CODE HERE
**inv=np.linalg.inv(a)
return np.matmul(inv,b)**


print(lin_eqn(np.array([[1, 2], [3, 4]]),np.array([8, 18])))
#It prints [2. 3.]

assert lin_eqn(np.array([[1, 2], [3, 4]]),np.array([8, 18])).tolist() == [2.0000000000000004, 2.9999999999999996]

我的作业中给出的断言语句导致答案不匹配。它抛出一个错误,因为 [2. 3.] 不等于 [2.0000000000000004, 2.9999999999999996] 我无法解决这个问题。请帮忙。

最佳答案

  1. 不要反转矩阵来求解线性方程组,而是使用 np.linalg.solve。
  2. 会有舍入误差,而不是检查是否相等,您宁愿检查您的解决方案和引用的范数是否小于给定的(小)公差。即:

    断言 np.linalg.norm(lin_eqn(a, b) - reference_sol) < 1e-12

reference_sol 也是一个数组。

关于python - 求解一对线性方程时的断言错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61057033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com