判断某点是否在圆形、三角形内

go语言实现的函数

计算两点距离,圆心与某点距离小于等于半径,计算某点和三角形三个点组成的三个小三角形的面积之和是否等于该三角形的面积。

package twod

import (
	"fmt"
	"math"
)

type Coordinate struct {
	Lat float64
	Lon float64
}

//compute the distance between two coordinates
func ComputeDistance(a Coordinate, b Coordinate) float64 {
	return math.Sqrt(math.Pow(b.Lon-a.Lon, 2) + math.Pow(b.Lat-a.Lat, 2))
}

func InsideCircle(center Coordinate, radius float64, p Coordinate) bool {
	return ComputeDistance(center, p) <= radius
}

//compute the angel of ∠BAC
func ComputeAngle(a Coordinate, b Coordinate,c Coordinate) float64{
	lenAC :=ComputeDistance(a,c)
	lenAB :=ComputeDistance(a,b)
	lenBC :=ComputeDistance(b,c)
	molecule :=math.Pow(lenAB,2) + math.Pow(lenAC,2) - math.Pow(lenBC,2)
	denominator := 2*lenAB*lenAC
	return math.Acos(molecule/denominator)*180/math.Pi
}

//compute the area of a triangle
func ComputeArea(a Coordinate, b Coordinate,c Coordinate) float64{
	lenCA :=ComputeDistance(c,a)
	lenCB :=ComputeDistance(c,b)
	lenAB :=ComputeDistance(b,a)

	if lenCA+lenCB > lenAB && lenCB+lenAB > lenCA &&lenAB+lenCA < lenCB {
		panic("not a triangle")
	}

	perimeter :=lenCA+lenCB+lenAB
	return math.Sqrt(perimeter/2*(perimeter/2-lenCA)*(perimeter/2-lenCB)*(perimeter/2-lenAB))
}

func InsideTriangle(a Coordinate, b Coordinate,c Coordinate, p Coordinate) bool {
	areaABP :=ComputeArea(a,b,p)
	areaBCP:=ComputeArea(b,c,p)
	areaCAP :=ComputeArea(c,a,p)

	areaABC :=ComputeArea(a,b,c)
	return fmt.Sprintf("%.3f", areaABP+areaBCP+areaCAP) == fmt.Sprintf("%.3f", areaABC)
}

调用示例:

length := twod.ComputeDistance(
		twod.Coordinate{Lon: 0.3,Lat: 0.3},
		twod.Coordinate{Lon: 1,Lat: 1})
	log.Printf("%.2f", length)

	log.Println(twod.InsideCircle(twod.Coordinate{Lon: 0, Lat: 0}, 5,
		twod.Coordinate{Lon: 0, Lat: 4.8}))

	inside := twod.InsideTriangle(
		twod.Coordinate{Lon: 0, Lat: 0},
		twod.Coordinate{Lon: 50, Lat: 50},
		twod.Coordinate{Lon: 100, Lat: 0},
		twod.Coordinate{Lon: 2, Lat: 2})
	log.Println(inside)

	angel := twod.ComputeAngle(twod.Coordinate{Lon: 0, Lat: 0},
		twod.Coordinate{Lon: 1, Lat: 0},
		twod.Coordinate{Lon: 1, Lat: 3})
	log.Printf("%.2f", angel)