# geoalg / geoalg / util.py

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76``` ```#!/usr/bin/env python #coding:utf-8 # Author: mozman # Purpose: util functions # module belongs to package geoalg # Created: 28.02.2010 # License: GPLv3 from __future__ import division from __future__ import print_function from __future__ import unicode_literals from __future__ import absolute_import import math from geoalg import equals_almost HALF_PI = math.pi / 2. THREE_PI_HALF = 1.5 * math.pi DOUBLE_PI = 2. * math.pi almost_equal = equals_almost def almost_equal_vectors(v1, v2, places=6): return all(almost_equal(a, b, places) for a, b in zip(v1, v2)) def distance(p1, p2): """ Distance between p1 and p2. """ dx = p1[0] - p2[0] dy = p1[1] - p2[1] try: dz = p1[2] - p2[2] except IndexError: dz = 0. return (dx**2 + dy**2 + dz**2) ** .5 def mid_point(p1, p2): """ Returns the midpoint between p1 and p2 as 3-tuple. """ x = (p1[0] + p2[0]) / 2.0 y = (p1[1] + p2[1]) / 2.0 try: z = (p1[2] + p2[2]) / 2.0 except IndexError: z = 0. return x, y, z ## {{{ http://code.activestate.com/recipes/578231/ (r1) def memodict(f): """ Memoization decorator for a function taking a single argument """ class memodict(dict): def __missing__(self, key): ret = self[key] = f(key) return ret return memodict().__getitem__ ## end of http://code.activestate.com/recipes/578231/ }}} def centroid2d(points): sumx, sumy = 0., 0. count = 0 for point in points: sumx += point[0] sumy += point[1] count += 1 return sumx/count, sumy/count def centroid3d(points): sumx, sumy, sumz = 0., 0., 0. count = 0 for point in points: sumx += point[0] sumy += point[1] sumz += point[2] count += 1 return sumx/count, sumy/count, sumz/count ```