简体   繁体   English

将字符串格式的方程转换为 Line(geometry) 对象

[英]Convert equation in string format to Line(geometry) object

I have a linear equation like y = "x+1" in my python code.我的 python 代码中有一个线性方程,如y = "x+1" I want to convert this equation into an object of class Line in sympy as sympy.geometry.line .我想将这个方程转换为sympy.geometry.line Line 类的对象,如sympy.geometry.line I tried to parse the string into sympy expression by doing:我尝试通过执行以下操作将字符串解析为 sympy 表达式:

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'> .和输出是<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?如果不可能,那么有没有办法将其转换为类的另一个对象,例如 python scipy Line 对象?

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.我没有看到从方程创建 Line 对象的简单方法。 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我认为最简单的方法是从两个 x 值(比如 0 和 1)创建两个 Point 对象,然后从这些值创建线,比如

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.此功能现在存在于 Sympy 中,供其他任何找到此帖子的人使用。

I tested this in Sympy 1.5.1我在 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))
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 1 x + 0 y - 100
outputs产出
ValueError: could not find y值错误:找不到 y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM