How to factor a vector (times it by itself a set number of times)?

80 Views Asked by At

How do I factor a vector, so take a vector and multiply by itself a number of times. I tried vec=vector**4 but get:

Runtime error (TypeErrorException): unsupported operand type(s) for **: 'Vector3d' and 'int'

1

There are 1 best solutions below

1
On

Assuming Vector3d is a type you designed yourself, you need to add support for ** explicitly.

If you look at the documentation for Emulating numeric types, you'll see that the method you need to write is:

object.__pow__(self, other[, modulo])

If you're confused by that third argument, __pow__ is used not only for the ** operator, but also for the pow function, which takes an optional third argument for modular exponentiation. If you don't want to support that, you can ignore it.

Now, how do you implement vector exponentiation? Well, if you only care about whole number powers, you can always do it through repeated cross-product. Assuming you've defined the * operator to mean cross-product:

class Vector3d(object):
    # ... other methods ...
    def __pow__(self, power):
        if not isinstance(power, numbers.Integral) or other < 0:
            # give power.__rpow__ a chance, just in case...
            return NotImplemented
        result = type(self)(1, 1, 1)
        for _ in range(power):
            result *= self
        return result

If you want to be able to raise vectors to real, complex, or vector powers, then there are a few different ways to define those things, and if you don't know which one you want, you probably need to ask about it on Math rather than StackOverflow.