This recipe implements vectors in pure Python and does not use "C" for speed enhancements. As a result, much effort has gone towards optimizing the instructions for the class methods. There are a few things that have yet to be improved, but it is being posted as an RFC. Comments on the structure, method names, and coding technique are requested for change. Once this code is standardized, work may commence on writing Vector3, Vector4, and VectorX. Please note that there is a difference between the "direction" and "degrees" properties.
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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 | from math import *
from functools import wraps
################################################################################
def autocast(method): # Optional method decorator
@wraps(method)
def wrapper(self, obj):
try:
return method(self, self.__class__(*obj))
except TypeError:
return method(self, obj)
return wrapper
################################################################################
def Polar2(magnitude, degrees):
x = magnitude * sin(radians(degrees))
y = magnitude * cos(radians(degrees))
return Vector2(x, y)
################################################################################
class Vector2:
__slots__ = 'x', 'y'
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Vector2({!r}, {!r})'.format(self.x, self.y)
def polar_repr(self):
x, y = self.x, self.y
magnitude = hypot(x, y)
angle = degrees(atan2(x, y)) % 360
return 'Polar2({!r}, {!r})'.format(magnitude, angle)
# Rich Comparison Methods
def __lt__(self, obj):
if isinstance(obj, Vector2):
x1, y1, x2, y2 = self.x, self.y, obj.x, obj.y
return x1 * x1 + y1 * y1 < x2 * x2 + y2 * y2
return hypot(self.x, self.y) < obj
def __le__(self, obj):
if isinstance(obj, Vector2):
x1, y1, x2, y2 = self.x, self.y, obj.x, obj.y
return x1 * x1 + y1 * y1 <= x2 * x2 + y2 * y2
return hypot(self.x, self.y) <= obj
def __eq__(self, obj):
if isinstance(obj, Vector2):
return self.x == obj.x and self.y == obj.y
return hypot(self.x, self.y) == obj
def __ne__(self, obj):
if isinstance(obj, Vector2):
return self.x != obj.x or self.y != obj.y
return hypot(self.x, self.y) != obj
def __gt__(self, obj):
if isinstance(obj, Vector2):
x1, y1, x2, y2 = self.x, self.y, obj.x, obj.y
return x1 * x1 + y1 * y1 > x2 * x2 + y2 * y2
return hypot(self.x, self.y) > obj
def __ge__(self, obj):
if isinstance(obj, Vector2):
x1, y1, x2, y2 = self.x, self.y, obj.x, obj.y
return x1 * x1 + y1 * y1 >= x2 * x2 + y2 * y2
return hypot(self.x, self.y) >= obj
# Boolean Operation
def __bool__(self):
return self.x != 0 or self.y != 0
# Container Methods
def __len__(self):
return 2
def __getitem__(self, index):
return (self.x, self.y)[index]
def __setitem__(self, index, value):
temp = [self.x, self.y]
temp[index] = value
self.x, self.y = temp
def __iter__(self):
yield self.x
yield self.y
def __reversed__(self):
yield self.y
yield self.x
def __contains__(self, obj):
return obj in (self.x, self.y)
# Binary Arithmetic Operations
def __add__(self, obj):
if isinstance(obj, Vector2):
return Vector2(self.x + obj.x, self.y + obj.y)
return Vector2(self.x + obj, self.y + obj)
def __sub__(self, obj):
if isinstance(obj, Vector2):
return Vector2(self.x - obj.x, self.y - obj.y)
return Vector2(self.x - obj, self.y - obj)
def __mul__(self, obj):
if isinstance(obj, Vector2):
return Vector2(self.x * obj.x, self.y * obj.y)
return Vector2(self.x * obj, self.y * obj)
def __truediv__(self, obj):
if isinstance(obj, Vector2):
return Vector2(self.x / obj.x, self.y / obj.y)
return Vector2(self.x / obj, self.y / obj)
def __floordiv__(self, obj):
if isinstance(obj, Vector2):
return Vector2(self.x // obj.x, self.y // obj.y)
return Vector2(self.x // obj, self.y // obj)
def __mod__(self, obj):
if isinstance(obj, Vector2):
return Vector2(self.x % obj.x, self.y % obj.y)
return Vector2(self.x % obj, self.y % obj)
def __divmod__(self, obj):
if isinstance(obj, Vector2):
return (Vector2(self.x // obj.x, self.y // obj.y),
Vector2(self.x % obj.x, self.y % obj.y))
return (Vector2(self.x // obj, self.y // obj),
Vector2(self.x % obj, self.y % obj))
def __pow__(self, obj):
if isinstance(obj, Vector2):
return Vector2(self.x ** obj.x, self.y ** obj.y)
return Vector2(self.x ** obj, self.y ** obj)
def __lshift__(self, obj):
if isinstance(obj, Vector2):
return Vector2(self.x << obj.x, self.y << obj.y)
return Vector2(self.x << obj, self.y << obj)
def __rshift__(self, obj):
if isinstance(obj, Vector2):
return Vector2(self.x >> obj.x, self.y >> obj.y)
return Vector2(self.x >> obj, self.y >> obj)
def __and__(self, obj):
if isinstance(obj, Vector2):
return Vector2(self.x & obj.x, self.y & obj.y)
return Vector2(self.x & obj, self.y & obj)
def __xor__(self, obj):
if isinstance(obj, Vector2):
return Vector2(self.x ^ obj.x, self.y ^ obj.y)
return Vector2(self.x ^ obj, self.y ^ obj)
def __or__(self, obj):
if isinstance(obj, Vector2):
return Vector2(self.x | obj.x, self.y | obj.y)
return Vector2(self.x | obj, self.y | obj)
# Binary Arithmetic Operations (with reflected operands)
def __radd__(self, obj):
return Vector2(obj + self.x, obj + self.y)
def __rsub__(self, obj):
return Vector2(obj - self.x, obj - self.y)
def __rmul__(self, obj):
return Vector2(obj * self.x, obj * self.y)
def __rtruediv__(self, obj):
return Vector2(obj / self.x, obj / self.y)
def __rfloordiv__(self, obj):
return Vector2(obj // self.x, obj // self.y)
def __rmod__(self, obj):
return Vector2(obj % self.x, obj % self.y)
def __rdivmod__(self, obj):
return (Vector2(obj // self.x, obj // self.y),
Vector2(obj % self.x, obj % self.y))
def __rpow__(self, obj):
return Vector2(obj ** self.x, obj ** self.y)
def __rlshift__(self, obj):
return Vector2(obj << self.x, obj << self.y)
def __rrshift__(self, obj):
return Vector2(obj >> self.x, obj >> self.y)
def __rand__(self, obj):
return Vector2(obj & self.x, obj & self.y)
def __rxor__(self, obj):
return Vector2(obj ^ self.x, obj ^ self.y)
def __ror__(self, obj):
return Vector2(obj | self.x, obj | self.y)
# Augmented Arithmetic Assignments
def __iadd__(self, obj):
if isinstance(obj, Vector2):
self.x += obj.x
self.y += obj.y
else:
self.x += obj
self.y += obj
return self
def __isub__(self, obj):
if isinstance(obj, Vector2):
self.x -= obj.x
self.y -= obj.y
else:
self.x -= obj
self.y -= obj
return self
def __imul__(self, obj):
if isinstance(obj, Vector2):
self.x *= obj.x
self.y *= obj.y
else:
self.x *= obj
self.y *= obj
return self
def __itruediv__(self, obj):
if isinstance(obj, Vector2):
self.x /= obj.x
self.y /= obj.y
else:
self.x /= obj
self.y /= obj
return self
def __ifloordiv__(self, obj):
if isinstance(obj, Vector2):
self.x //= obj.x
self.y //= obj.y
else:
self.x //= obj
self.y //= obj
return self
def __imod__(self, obj):
if isinstance(obj, Vector2):
self.x %= obj.x
self.y %= obj.y
else:
self.x %= obj
self.y %= obj
return self
def __ipow__(self, obj):
if isinstance(obj, Vector2):
self.x **= obj.x
self.y **= obj.y
else:
self.x **= obj
self.y **= obj
return self
def __ilshift__(self, obj):
if isinstance(obj, Vector2):
self.x <<= obj.x
self.y <<= obj.y
else:
self.x <<= obj
self.y <<= obj
return self
def __irshift__(self, obj):
if isinstance(obj, Vector2):
self.x >>= obj.x
self.y >>= obj.y
else:
self.x >>= obj
self.y >>= obj
return self
def __iand__(self, obj):
if isinstance(obj, Vector2):
self.x &= obj.x
self.y &= obj.y
else:
self.x &= obj
self.y &= obj
return self
def __ixor__(self, obj):
if isinstance(obj, Vector2):
self.x ^= obj.x
self.y ^= obj.y
else:
self.x ^= obj
self.y ^= obj
return self
def __ior__(self, obj):
if isinstance(obj, Vector2):
self.x |= obj.x
self.y |= obj.y
else:
self.x |= obj
self.y |= obj
return self
# Unary Arithmetic Operations
def __pos__(self):
return Vector2(+self.x, +self.y)
def __neg__(self):
return Vector2(-self.x, -self.y)
def __invert__(self):
return Vector2(~self.x, ~self.y)
def __abs__(self):
return Vector2(abs(self.x), abs(self.y))
# Virtual "magnitude" Attribute
def __fg_ma(self):
return hypot(self.x, self.y)
def __fs_ma(self, value):
x, y = self.x, self.y
temp = value / hypot(x, y)
self.x, self.y = x * temp, y * temp
magnitude = property(__fg_ma, __fs_ma, doc='Virtual "magnitude" Attribute')
# Virtual "direction" Attribute
def __fg_di(self):
return atan2(self.y, self.x)
def __fs_di(self, value):
temp = hypot(self.x, self.y)
self.x, self.y = cos(value) * temp, sin(value) * temp
direction = property(__fg_di, __fs_di, doc='Virtual "direction" Attribute')
# Virtual "degrees" Attribute
def __fg_de(self):
return degrees(atan2(self.x, self.y)) % 360
def __fs_de(self, value):
temp = hypot(self.x, self.y)
self.x, self.y = sin(radians(value)) * temp, cos(radians(value)) * temp
degrees = property(__fg_de, __fs_de, doc='Virtual "degrees" Attribute')
# Virtual "xy" Attribute
def __fg_xy(self):
return self.x, self.y
def __fs_xy(self, value):
self.x, self.y = value
xy = property(__fg_xy, __fs_xy, doc='Virtual "xy" Attribute')
# Virtual "yx" Attribute
def __fg_yx(self):
return self.y, self.x
def __fs_yx(self, value):
self.y, self.x = value
yx = property(__fg_yx, __fs_yx, doc='Virtual "yx" Attribute')
# Unit Vector Operations
def unit_vector(self):
x, y = self.x, self.y
temp = hypot(x, y)
return Vector2(x / temp, y / temp)
def normalize(self):
x, y = self.x, self.y
temp = hypot(x, y)
self.x, self.y = x / temp, y / temp
return self
# Vector Multiplication Operations
def dot_product(self, vec):
return self.x * vec.x + self.y * vec.y
def cross_product(self, vec):
return self.x * vec.y - self.y * vec.x
# Geometric And Physical Reflections
def reflect(self, vec):
x1, y1, x2, y2 = self.x, self.y, vec.x, vec.y
temp = 2 * (x1 * x2 + y1 * y2) / (x2 * x2 + y2 * y2)
return Vector2(x2 * temp - x1, y2 * temp - y1)
def bounce(self, vec):
x1, y1, x2, y2 = self.x, self.y, +vec.y, -vec.x
temp = 2 * (x1 * x2 + y1 * y2) / (x2 * x2 + y2 * y2)
return Vector2(x2 * temp - x1, y2 * temp - y1)
# Standard Vector Operations
def project(self, vec):
x, y = vec.x, vec.y
temp = (self.x * x + self.y * y) / (x * x + y * y)
return Vector2(x * temp, y * temp)
def rotate(self, vec):
x1, y1, x2, y2 = self.x, self.y, vec.x, vec.y
return Vector2(x1 * x2 + y1 * y2, y1 * x2 - x1 * y2)
def interpolate(self, vec, bias):
a = 1 - bias
return Vector2(self.x * a + vec.x * bias, self.y * a + vec.y * bias)
# Other Useful Methods
def near(self, vec, dist):
x, y = self.x, self.y
return x * x + y * y <= dist * dist
def perpendicular(self):
return Vector2(+self.y, -self.x)
def subset(self, vec1, vec2):
x1, x2 = vec1.x, vec2.x
if x1 <= x2:
if x1 <= self.x <= x2:
y1, y2 = vec1.y, vec2.y
if y1 <= y2:
return y1 <= self.y <= y2
return y2 <= self.y <= y1
else:
if x2 <= self.x <= x1:
y1, y2 = vec1.y, vec2.y
if y1 <= y2:
return y1 <= self.y <= y2
return y2 <= self.y <= y1
return False
# Synonymous Definitions
copy = __pos__
inverse = __neg__
unit = unit_vector
dot = dot_product
cross = cross_product
lerp = interpolate
perp = perpendicular
|
Would someone mind testing the following code for their respective speeds?
timeit.Timer('test1(1.2, 4.3)', 'def test1(a, b): return (a * a + b * b) ** 0.5').timeit()
timeit.Timer('test2(1.2, 4.3)', 'import math\ndef test2(a, b, h=math.hypot): return h(a, b)').timeit()
Gabriel Genellina pointed out that the second should be faster, but the opposite appears to be true while running on my computer.
Here's what I get for those lines:
MacBook Pro (Core2Duo 2.6) running 10.6
Compaq Presario CQ60
Genuine Intel(R) CPU - 585 @ 2.16GHz, 2161 Mhz, 1 Core(s), 1 Logical Processor(s)
Microsoft(R) Windows Vista(TM) Home Basic
Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32
>>> import timeit
>>> timeit.Timer('test1(1.2, 4.3)', 'def test1(a, b): return (a * a + b * b) ** 0.5').timeit()
0.5237614696839962
>>> timeit.Timer('test2(1.2, 4.3)', 'import math\ndef test2(a, b, h=math.hypot): return h(a, b)').timeit()
0.8653614495697077
Can anyone explain the difference in time (or the "correct" syntax for post code block in the comments)?
Those numbers are mostly consistent at a ratio of difference at about 1.6; the second is never faster here.
Are most of you running on Linux kernels? Many people run Python in Linux, and I have heard that Mac uses it now.
OSX 10.5 came with 2.4 and 2.5, 10.6 comes with 2.4, 2.5 and 2.6 (which is what I ran my tests on).
To get the code blocks working, you have to either indent 4 spaces, or replace the ">>>" (just re-type it, copying and pasting doesn't work for some reason).