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:


>>> 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) > 0Point est au dessus de la ligne ?: False>>> print 'Point est en dessous de la ligne ?: ', yp - function(xp) < 0Point est en dessous de la ligne ?: True>>> print 'Point est sur la ligne ?: ', yp - function(xp) == 0Point est sur la ligne ?: False
Python code to plot figure 1 and 2 using matplotlib:
import matplotlib.pyplot as pltimport numpy as np#----- Straight Line -----#def function( x ):return 0.5 * x + 2x = np.arange(0,10,0.1)y = function(x)plt.plot(x, y, 'k-', lw=2)#----- Point 1 -----#xp = 6.0yp = 3.0print 'Point est au dessus de la ligne ?: ', yp - function(xp) > 0print 'Point est en dessous de la ligne ?: ', yp - function(xp) < 0print 'Point est sur la ligne ?: ', yp - function(xp) == 0plt.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 |
