Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write vectors in an i,j,k format?

I get that it would be possible to do something like

i = numpy.array([1,0,0])
j = numpy.array([0,1,0])
k = numpy.array([0,0,1])

a = 2*i + 5*j + 9*k

but is it possible to harness a similar syntax to the way complex numbers are done, and create a class that can determine 2i + 5j + 9k is a member of my class, and automatically create it?

Or would it require altering the python interpreter by changing the way it parses files? I've had a look in the grammar file, but all i can see it alluding to is NUMBER, and j isn't mentioned once.

I've also looked in parsermodule.c, but couldn't easily spot anything in there that made it obvious how it could be done.

Does anyone know how this could be possible?

I should probably add that i'm not actually planning on doing this (unless by some miracle it turned out to not require recompiling my own version of python, which would be insane to do as anything other than an academic journey), but just out of curiosity about how the language works.

like image 305
will Avatar asked Nov 09 '22 22:11

will


1 Answers

You could write a class that inherits from numpy.ndarray (i.e. a subclass) that overrides the repr method (which is responsible for controlling how the object is printed to the console), as follows:

import numpy

class Vector3DDisplay(numpy.ndarray):

def __init__(self, vector):
    if len(vector) == 3:
        self.vec = numpy.array(vector)
    else:
        raise TypeError('Vector must be of length 3.')

def __repr__(self):
    return str(self.vec[0])+'*i + '+str(self.vec[1])+'*j + '+str(self.vec[2])+'*k '

You're probably noticing an obvious problem here: the actual vector is self.vec, not the object itself, so all of your numpy operations have to be done on the attribute self.vec. The reason with this is that numpy arrays are written in such a way that they are difficult to subclass (c.f. this question about subclassing C exentsions). Normally, you initialize an array with:

>>>> import numpy
>>>> numpy.ndarray(vector)

The problem is that np.array isn't actually a class, but a factory function for the numpy.ndarray class, which is initialized differently and is rarely used. You can't have an object inherit methods from a function, so the inheritance isn't straightforward.

like image 99
MTrenfield Avatar answered Nov 14 '22 22:11

MTrenfield