Skip to content

Instantly share code, notes, and snippets.

@simonjtyler
Created November 12, 2010 01:03
Show Gist options
  • Save simonjtyler/673553 to your computer and use it in GitHub Desktop.
Save simonjtyler/673553 to your computer and use it in GitHub Desktop.
IntersectQ: See if a line intersects with a point up to some precision
(* Written for http://stackoverflow.com/q/4126473/421225 *)
(* SlowIntersectQ is too slow to use in EdgeRenderingFunction *)
SlowIntersectQ[{start_,end_},pt_,r_?Positive]/;Length[start]==Length[end]==Length[pt]:=Module[{t},
TrueQ[NMinValue[{Norm[((1.-t)start+t end)-pt],0<t<1},t,WorkingPrecision->$MachinePrecision]<r]]
(* Since we only care about straight lines, here's a faster implementation *)
(* from: http://stackoverflow.com/q/849211/421225 *)
linDistance[{start_,end_},pt_]:=Module[{param},
param=((pt-start).(end-start))/Norm[end-start]^2;
Which[
param<0,EuclideanDistance[start,pt], (*If outside bounds*)
param>1,EuclideanDistance[end,pt],(*If outside bounds*)
True,EuclideanDistance[pt,start+param (end-start)] (*Normal distance*)
]];
IntersectQ[{start_,end_},pt_,r_?Positive]/;Length[start]==Length[end]==Length[pt]:=Module[{t},
TrueQ[linDistance[{start,end},pt]<r]]
(* Test the function *)
IntersectQ[{{-1,0},{1,0}},#,.05]&/@{{0,0},{0,0.01},{0,0.05},{0,0.1}}=={True,True,False,False}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment