Created
September 14, 2012 09:51
-
-
Save yoshihiro503/3721086 to your computer and use it in GitHub Desktop.
OCamlで、点と直線の距離、点と線分の距離、点と半直線の距離
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* ベクトルの内積 *) | |
let ( ** ) (x,y) (a,b) = x *. a +. y *. b | |
(* 2点間の距離 *) | |
let distance (x,y) (a,b) = sqrt ((x -. a) * (x -. a) + (y -. b) * (y -. b)) | |
(* 点(px,py) と 直線(x1,y1)(x2,y2)の距離 *) | |
let distance_to_line (x1,y1) (x2,y2) (px,py) = | |
let b, c = (x2-.x1,y2-.y1), (px-.x1,py-.y1) in | |
let dotprod = b ** c in | |
sqrt ((c ** c) -. dotprod *. dotprod /. (b ** b)) | |
(* 点(px,py) と 線分(x1,y1)(x2,y2)の距離 *) | |
let distance_to_segment (px,py) (x1,y1) (x2,y2) = | |
let b, c = (x2-.x1,y2-.y1), (px-.x1,py-.y1) in | |
let dotprod = b ** c in | |
if dotprod < 0 then | |
distance (px,py) (x1,y1) | |
else dotprod > c ** c then | |
distance (px,py) (x2,y2) | |
else | |
sqrt ((c ** c) -. dotprod *. dotprod /. (b ** b)) | |
(* 点(px,py) と (x1,y1)から伸びる半直線との距離 *) | |
let distance_to_halfline (px,py) (x1,y1) (x2,y2) = | |
let b, c = (x2-.x1,y2-.y1), (px-.x1,py-.y1) in | |
let dotprod = b ** c in | |
if dotprod < 0 then | |
distance (px,py) (x1,y1) | |
else | |
sqrt ((c ** c) -. dotprod *. dotprod /. (b ** b)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment