【问题标题】:How to get the integer part of the solution of system of linear equation using numpy?如何使用numpy获得线性方程组解的整数部分?
【发布时间】:2021-01-09 06:15:05
【问题描述】:
import numpy as np

# Linear Equations
# x+3y-2z=5
# 3x+5y+6z=7
# 2x+4y+3z=8

A = np.array([[1,3,-2], [3,5,6], [2,4,3]])
B = np.array([[5,7,8]])
B = B.T
ans = np.linalg.solve(A, B)
print(ans)

我想求解这些线性方程组并使用高斯消元法打印 x y 和 z 的值 正如预期的那样,输出是一个数组。

OUTPUT:    
[  [-15.]     
 [  8.]       
 [  2.]  ]

我只希望它是像 -15、8、2 这样的整数,这样我就可以打印出值 x=-15, y=8, z=2 如果我尝试将其转换为int(ans[0])(甚至是列表),但它给出的下限值分别为-14、7、1。 请告诉我如何将值 -15、8、2 作为整数获取。

PS:我尝试使用字符串并获得了所需的值,但这样做很乏味,直接获取整数以进行进一步操作会很棒。

【问题讨论】:

    标签: python python-3.x numpy type-conversion output


    【解决方案1】:

    问题是ans 中的结果是浮点数,结果实际上不是[-15, 8, 2],即使这是显示的内容。因此,当使用ans[0][0] 时,您会得到类似:-14.999999999999993

    现在,由于它不是整数,所以当使用int() 时,python 会自动向下舍入。这就是为什么你得到 -14 的原因。

    一种可能的解决方案是使用np.rint,它将numpy 数组中的元素四舍五入为最接近的整数。下面,列表也被展平为一维:

    ans = np.rint(ans).flatten()
    

    现在,可以使用 ans[0]ans[1] 等以整数形式访问元素。

    【讨论】:

      【解决方案2】:

      你实际上可以用一个简单的众所周知的函数来解决你的问题,比如round()

      import numpy as np
      
      # Linear Equations
      #  x + 3y - 2z = 5
      # 3x + 5y + 6z = 7
      # 2x + 4y + 3z = 8
      
      # Define the matrix system
      A = np.array([[1,3,-2], [3,5,6], [2,4,3]])
      B = np.array([[5,7,8]])
      B = B.T
      
      # Solve the system
      ans = np.linalg.solve(A, B)
      
      # OPTION 1: Nearest integers, but still float
      ans1 = ans.round()
      
      # OPTION 2: Nearest integers
      ans2 = ans.round().astype(int)
      

      正如 Shaido 之前所说,您可以添加 .flatten() 以便更轻松地访问答案值。

      希望这是有用的;)

      【讨论】:

      • 是的,很高兴了解各种技术,谢谢,它也有效!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多