I have a linear equation like y = "x+1"
in my python code. I want to convert this equation into an object of class Line in sympy as sympy.geometry.line
. I tried to parse the string into sympy expression by doing:
from sympy.parsing.sympy_parser import (parse_expr, standard_transformations, function_exponentiation, implicit_multiplication_application)
y = "2*x+1"
transformations = (standard_transformations + (implicit_multiplication_application,))
L2 = parse_expr(y, transformations=transformations)
print(type(L2))
and output is <class 'sympy.core.add.Add'>
.
I do not know what to do next to make it to object. If it is not possible, then is there a way to convert it into another object of a class, like a python scipy Line object?
I need this because I want to calculate the slope of the line, points lying on the line (points that satisfies the equation) to calculate lines parallel or perpendicular to this line.
I don't see a simple way to create a Line object from an equation. I think the simplest way to do it would be to create two Point objects from two x values (say 0 and 1) and create the line from those, like
p1 = Point(0, L2.subs(x, 0))
p2 = Point(1, L2.subs(x, 1))
Line(p1, p2)
This feature now exists in Sympy, for anyone else who finds this post.
I tested this in Sympy 1.5.1
Code:
from sympy import Line, symbols
a,b,c,x,y = symbols('a b c x y')
# Hardcoded line equation
line1 = Line(3*x + 1*y + 18)
print(line1)
# Set the line equation in code
a = 3; b = 1; c = 18
line2 = Line(a*x + b*y + c)
print(line2)
Output:
Line2D(Point2D(0, -18), Point2D(1, -21))
Line2D(Point2D(0, -18), Point2D(1, -21))
Unfortunately it fails for vertical lines:
1 x + 0 y - 100
outputs
ValueError: could not find y
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.