Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract coefficients from a line equation in python without using numpy?

I have 2 lists RED and BLUE in the form of (x,y) tuples and a list of line equations in the form of ax+by+c. My requirement is to extract the coefficients from each line equation and determine based on the plots for the 2 set of points whether the points are clearly separated on both sides of the line. Challenge is that I cannot use numpy.

My approach has been to zip the 2 lists RED and BLUE points using pyplot. Now I am trying to extract the coefficients using regular expression as below.

lines = ["1x+1y+0","1x-1y+0","1x+0y-3","0x+1y-0.5"]

for i in lines:
    z = re.match('(\d+)?(x)?\+(\d+)?(y)?\+(\d)?', i)

However, Im not able to use 'z' as it is of 'NoneType'. Even if I am able to use it somehow, I am not sure how to use the intercept and slope to determine that the RED and BLUE points are on either side of the line.

Any pointers are hugely appreciated.

Tried plotting the points using matplotlib

Red_x = [(x,y) for x,y in Red]
Blue_x = [(x,y) for x,y in Blue]

plt.plot(*zip(*Red_x),'or')
plt.scatter(*zip(*Blue_x))
like image 479
Kunal Chowdhury Avatar asked Jul 09 '19 08:07

Kunal Chowdhury


People also ask

How do you extract a coefficient in an equation in Python?

coeff(x, n) method. With the help of sympy. coeff(x, n) method, we are able to find the coefficient of variables in mathematical expressions.

How do you find the coefficient of a line in Python?

You can start with a simple pattern of [\d\. \-\+]+ . This will catch all coefficients assuming the coefficients are properly formatted (e.g. no double periods in digits).

How do I find the coefficient of a line?

A regression coefficient is the same thing as the slope of the line of the regression equation. The equation for the regression coefficient that you'll find on the AP Statistics test is: B1 = b1 = Σ [ (xi – x)(yi – y) ] / Σ [ (xi – x)2]. “y” in this equation is the mean of y and “x” is the mean of x.


1 Answers

I believe what you want to use is findall.

You can start with a simple pattern of [\d\.\-\+]+. This will catch all coefficients assuming the coefficients are properly formatted (e.g. no double periods in digits).

>>> lines = ["1x+1y+0", "1x-1y+0", "1x+0y-3", "0x+1y-0.5"]
>>> for i in lines:
...     z = re.findall(r'[\d\.\-\+]+', i)
...     print(z)
... 
['1', '+1', '+0']
['1', '-1', '+0']
['1', '+0', '-3']
['0', '+1', '-0.5']

Obviously, you'll have to do some additional parsing of the resulting list of strings to convert them to numbers, but that will be an exercise for you :)

like image 90
Scratch'N'Purr Avatar answered Oct 03 '22 02:10

Scratch'N'Purr