想法
受@ShubhamSrivastava 评论的启发,想法是:
基本原理
由于精确的 == 和 != 比较(映射键要求)不适用于浮点数,因此当 float32 始终四舍五入到有限的小数点时,此类比较更有意义。
实施
我通过这些方法将 Vertex 类型内的 float32 字段舍入到特定小数点:
// round floating point fields of my type to a specific decimal point
func vertRoundTo(vi Vertex, decimals uint32) (vo Vertex, err error) {
if vo.X, err = roundTo(vi.X, decimals); err != nil {
return Vertex{}, err
}
if vo.Y, err = roundTo(vi.Y, decimals); err != nil {
return Vertex{}, err
}
if vo.Z, err = roundTo(vi.Z, decimals); err != nil {
return Vertex{}, err
}
return
}
// round float32 to a specific decimal point
// https://stackoverflow.com/a/52048478/3405291
func roundTo(fi float32, decimals uint32) (fo float32, err error) {
if decimals < 1 {
err = errors.New("minimum decimal point is exceeded")
return
}
fo = float32(math.Round(float64(fi)*float64(decimals)) / float64(decimals))
return
}
我使用上面的方法是这样的:
// "cluster" is already filled with rounded floats
func (c *cluster) DoesClusterContainVertex(v Vertex) (does bool, err error) {
// coordinates would be rounded to a specific decimal point
// since exact == and != comparison is NOT proper for float
// such comparisons are required for map key
var vRound Vertex
if vRound, err = vertRoundTo(v, 4); err != nil {
return
}
if _, ok := c.verts[vRound]; ok {
// cluster contains vertex
does = true
}
return
}