pythonsympyequation

How to derive the coefficients of the sympy equation


There is such a code:

from sympy import Point3D, Plane

p1 = Plane(Point3D(0, 0, 1),
           Point3D(0, 1, 0),
           Point3D(1, 0, 0))
p2 = p1.equation()
print(p2)

The program outputs the result: -10*x - 10*y - z + 10

Here a = -10, b=-10, c = -1 and d = 10.

Is there any method to output the coefficients individually?

Since I did not find such a method, I wrote a parser that does this, but since the program does not produce the result in the same format, the parser requires a lot of refinement or even reworking.


Solution

  • I'm not aware of a function that directly gives the coefficients in the desired form. Internally, the plane is represented by a point and a normal vector. p1.args returns them as a tuple. Your a, b, c form the normal. The negative of the dot product between the normal and a point on the plane gives d. Of course, the same equation can be multiplied by an arbitrary non-zero value.

    from sympy import Point3D, Plane
    
    p1 = Plane(Point3D(0, 0, 1),
               Point3D(0, 1, 0),
               Point3D(1, 0, 0))
    
    point, normal = p1.args
    p2 = p1.equation()
    print(f'{p2 = }')
    a, b, c = normal
    d = - Point3D(normal).dot(point)
    print(f'{a = }, {b = }, {c = }, {d = }')
    

    Output

    p2 = -x - y - z + 1
    a = -1, b = -1, c = -1, d = 1
    

    Alternatively, you can work with explicit names for the symbols in the equation. And then get a as the coefficient of x. d will be the value when x, y and z are zero:

    from sympy import Point3D, Plane
    from sympy.abc import x, y, z
    
    p1 = Plane(Point3D(0, 0, 1),
               Point3D(0, 1, 0),
               Point3D(1, 0, 0))
    
    p2 = p1.equation(x=x, y=y, z=z)
    print(f'{p2 = }')
    print(f'a = {p2.coeff(x)}, b = {p2.coeff(y)}, c = {p2.coeff(z)}, d = {p2.subs({x: 0, y: 0, z: 0})}')
    

    Output:

    p2 = -x - y - z + 1
    a = -1, b = -1, c = -1, d = 1