【问题标题】:Solve for an equation of a plane in Python (like in Matlab)在 Python 中求解平面方程(如在 Matlab 中)
【发布时间】:2012-08-14 22:44:45
【问题描述】:

我有一个数据集,我正试图从中获取平面方程。 即:a*x + b*y + c = z 在我的例子中,dT = x,dTa = y,Constant = c,dV = z。

我可以在 Matlab 中很容易地做到这一点,代码:

dT = [8.5; 3.5; .4; 12.9]

dT =

    8.5000
    3.5000
    0.4000
   12.9000

dTa = [8.5; 18; 22; 34.9]

dTa =

    8.5000
   18.0000
   22.0000
   34.9000

dV = [3; 1; .5; 3]

dV =

    3.0000
    1.0000
    0.5000
    3.0000

Constant = ones(size(dT))

Constant =

     1
     1
     1
     1

coefficients = [dT dTa Constant]\dV

coefficients =

    0.2535
   -0.0392
    1.0895

所以,这里的系数 = (a, b, c)。

在 Python 中是否有等效的方法来执行此操作? 我一直在尝试使用 numpy 模块(numpy.linalg),但效果不佳。 一方面,矩阵必须是正方形的,即便如此,它也不能给出很好的答案。例如:

错误:

>>> dT
[8.5, 3.5, 0.4, 12.9]
>>> dTa
[8.5, 18, 22, 34.9]
>>> dV
[3, 1, 0.5, 3]
>>> Constant
array([ 1.,  1.,  1.,  1.])
>>> numpy.linalg.solve([dT, dTa, Constant], dV)

Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    numpy.linalg.solve([dT, dTa, Constant], dV)
  File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 312, in solve
    _assertSquareness(a)
  File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 160, in _assertSquareness
    raise LinAlgError, 'Array must be square'
LinAlgError: Array must be square

使用方阵:

>>> dT
array([  8.5,   3.5,  12.9])
>>> dTa
array([  8.5,  18. ,  34.9])
>>> dV
array([3, 1, 3])
>>> Constant
array([ 1.,  1.,  1.])
>>> numpy.linalg.solve([dT, dTa, Constant], dV)
array([ 2.1372267 ,  2.79746835, -1.93469505])

这些甚至与我之前得到的值都不接近!!

有什么想法吗?任何建议表示赞赏。

【问题讨论】:

  • 在你对问题的解释中,你的意思不是dT = x, dTa = y吗?
  • 对了,我完全搞砸了。现在将进行编辑。

标签: python matlab equation solver plane


【解决方案1】:

在第一个示例中,您需要使用numpy.linalg.lstsq。无论哪种方式,您似乎都混淆了矩阵的行和列。使用 numpy.linalg.solve(zip(dT, dTa, Constant), dV) 之类的东西修复它。

【讨论】:

  • 对,我其实是用 scipy.array(dT).transpose() 来翻转它们的。
【解决方案2】:

所以,我找到了这张照片

并对其进行了调整以包含一个常量。这是我解决的代码:

    X = 0
    XX = 0
    XY = 0
    XZ = 0

    Y = 0
    YY = 0
    YZ = 0

    Z = 0

    for j in range(0, len(dTemp)):
        X = X + dTemp[j]
        XX = XX + (dTemp[j] * dTemp[j])
        XY = XY + (dTemp[j] * dTempA[j])
        XZ = XZ + (dTemp[j] * Applied[j])

        Y = Y + dTempA[j]
        YY = YY + (dTempA[j] * dTempA[j])
        YZ = YZ + (dTempA[j] * Applied[j])

        Z = Z + Applied[j]


    lhs = numpy.array([[XX, XY, X], [XY, YY, Y], [X, Y, 1]]) 
    rhs = numpy.array([XZ,  YZ, Z])

    coefficients = numpy.linalg (lhs, rhs)

    a = coefficients[0]
    b = coefficients[1]
    c = coefficients[2]

我认为这成功了!仍然,值有点偏离,但可能是因为 Matlab 使用了不同的算法?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多