How to check if a point is below or above a straight line using python ?

Published: February 18, 2019

DMCA.com Protection Status

Example of how to check if a point is below or above a straight line using python ? Let's consider a line of equation y=f(x)=a*x+b, a point P with coordinates (xp,yp) is below the line if:

yp - ( a * xp + b ) < 0

or:

yp - f(xp) < 0

A point P with coordinates (xp,yp) is above the line if

yp - ( a * xp + b ) > 0

or:

yp - f(xp) > 0

A point P is on the line if and only if:

yp - f(xp) = 0

Example of python code to test if above or below a straight line:

Figure 1: How to check if a point is below or above a straight line using python ?: Example with P(6,3) and the line of equation y=0.5*x+2
Figure 1: How to check if a point is below or above a straight line using python ?: Example with P(6,3) and the line of equation y=0.5*x+2

Figure 2: How to check if a point is below or above a straight line using python ?: Example 1 with P(9,9) and the line of equation y=0.5*x+2
Figure 2: How to check if a point is below or above a straight line using python ?: Example 1 with P(9,9) and the line of equation y=0.5*x+2

>>> import numpy as np
 >>> def function( x ):
...     return 0.5 * x + 2
... 
 >>> x = np.arange(0,10,0.1)
 >>> y = function(x)
 >>> xp = 6.0 
 >>> yp = 3.0 
 >>> print 'Point est au dessus de la ligne ?: ', yp - function(xp) > 0 
 Point est au dessus de la ligne ?:  False
 >>> print 'Point est en dessous de la ligne ?: ', yp - function(xp) < 0 
 Point est en dessous de la ligne ?:  True
 >>> print 'Point est sur la ligne ?: ', yp - function(xp) == 0 
 Point est sur la ligne ?:  False

Python code to plot figure 1 and 2 using matplotlib:

import matplotlib.pyplot as plt
import numpy as np

#----- Straight Line -----#

def function( x ):
    return 0.5 * x + 2

x = np.arange(0,10,0.1)
y = function(x)

plt.plot(x, y, 'k-', lw=2)

#----- Point 1 -----#

xp = 6.0 
yp = 3.0

print 'Point est au dessus de la ligne ?: ', yp - function(xp) > 0 
print 'Point est en dessous de la ligne ?: ', yp - function(xp) < 0 
print 'Point est sur la ligne ?: ', yp - function(xp) == 0

plt.scatter(xp,yp)
plt.plot( (xp,xp), (0,yp), 'b--', lw=1) 
plt.plot( (0,xp), (yp,yp), 'b--', lw=1) 
plt.plot( (0,xp), (function(xp),function(xp)), 'b--', lw=1) 
plt.plot( (xp,xp), (0,function(xp)), 'b--', lw=1) 
plt.text( xp+0.2, yp, 'P') 
plt.text( xp+0.2, 0.2, 'xp') 
plt.text( -0.4, yp, 'yp') 
plt.text( -0.6, function(xp), 'f(xp)')

plt.xlim(0,10)
plt.ylim(0,10)

plt.savefig('output.png')
plt.show()

References

Links Site
Point par rapport à une droite developpez
Image

of