Basic vector math

Hye Guys, I would like to ask a question regarding python, how I can translate the following into javascript without using any external math libraries:

class Vector(object):
    def __init__(self, coordinates):
        try:
            if not coordinates:
                raise ValueError
            self.coordinates = tuple(coordinates)
            self.dimension = len(coordinates)

        except ValueError:
            raise ValueError('The coordinates must be nonempty')

        except TypeError:
            raise TypeError('The coordinates must be an iterable')


    def __str__(self):
        return 'Vector: {}'.format(self.coordinates)


    def __eq__(self, v):
        return self.coordinates == v.coordinates

    def plus(self, v):
      newCoordinates = [x+y for x,y in zip(self.coordinates, v.coordinates)]
      return Vector(newCoordinates)

    def times_scalar(self, c):
      newCoordinates = [c*x for x in self.coordinates]
      return Vector(newCoordinates)

    def minus(self, v): 
      return self.plus(v.times_scalar(-1))


a = Vector([8.218, -9.341])
b = Vector([-1.129, 2.111])
c = Vector([7.119, 8.215])
d = Vector([-8.223, 0.878])
e = Vector([1.671, -1.012, -0.318])
scalar = 7.41


print("vector a plus vector b: " + a.plus(b).__str__())
print("vector c minus vector d: " + c.minus(d).__str__())
print("vector e grow by scalar c: " + e.times_scalar(scalar).__str__())```

I see I should just stop being lazy and apply what ive been studying on the fcc curriculum, looking at again this prob is not that hard.
Here is the scalar:

function scalar(Vect, mult){ const map1 = Vect.map(x => x * mult); console.log(map1); } scalar([1.671, -1.012, -0.318],7.41);

I will do the rest and get back to this thread if anyone replies. and if anyone is interested its the Udacity linear algebra course.

Thing is I was confused about is the zip method as I see its needed for both plus and subtraction (even though minus function isnt using it its still using it vicariously through its use of plus) … But I just found this online so I think I have the tools necessary now.

zip method jscript

class Vector {
    // like Python __init__
    constructor(coordinates) {
        this.coordinates = [...coordinates];
        this.dimension = this.coordinates.length;
    }

    // Call with: vector.str
    get str() {return `Vector: ${this.coordinates}`}

    // return number of dimensions: vector.dim
    get dim() {return this.dimension}

    // return coordinates as Array for iteration
    // Call with: vector.coords
    get coords() {return this.coordinates}

    // To update a coordinate
    coordinate(index, newCoordinate) {this.coordinates[index] = newCoordinate}

    //  Coordinates generator:
    // let generator = vector.gen()
    // generator.next().value
    * gen() {
        let i = 0;
        while(true) {
            yield this.coordinates[i];
            i++;
        }
    }

    // JS comparison operators cannot compare Arrays element-wise like pythons listA == listB
    // every() checks each element individually
    eq(v) {return this.coordinates.every((x, i) => x === v.coords[i])}

    // map in place of Python list comprehension
    plus(v) {return new Vector(this.coordinates.map((x, i) => v.coords[i] ? x + v.coords[i] : x))}

    timesScalar(c) {return new Vector(this.coordinates.map(x => x * c))}

    
    // using the map() alternative might be faster for large vectors as it only constructs a Vector object once
    // minus(v) {return new Vector(this.coordinates.map((x, i) => v.coords[i] ? x - v.coords[i] : x))}
    minus(v) {return this.plus(v.timesScalar(-1))}
}


let a = new Vector([8.218, -9.341]),
    b = new Vector([-1.129, 2.111]),
    c = new Vector([7.119, 8.215]),
    d = new Vector([-8.223, 0.878]),
    e = new Vector([1.671, -1.012, -0.318]),
    scalar = 7.41;

console.log("vector a plus vector b: " + a.plus(b).str);
console.log("vector c minus vector d: " + c.minus(d).str);
console.log("vector e grow by scalar: " + e.timesScalar(scalar).str);

1 Like

Thank you for this code. im going to go over it and reply to this thread with any additional questions related to vector math.

Hi, I just started this course and I am having a hard time understanding the times scalar function? Would someone be able to walk me through what is happening here.

greetings Jumper,
Ive not done this course, nor have I studied linear algebra, and I dont have any experience with python either, but I will try to explain it to you.

the scalar scales the vector. multiplying by the scalar does not change the direction but will change its magnitude (scale it up). Unless its a negative, then it will switch its direction.

if you think of the vector as an array of points plotted on the graph it makes sense that you are taking some vector and multiplying each element inside said array by some constant and then you will want to be returning some new vector. and thats basically all thats going on…

for me it is better in javascript look for a moment @kylec code what he wrote is clear:

    timesScalar(c) {return new Vector(this.coordinates.map(x => x * c))}

so if you have some vector class that your using as a template and you instantiate a new vector with it then you will have some method that is inherited from the class, this method was named timesScalar, and you can call that method on your instantated vector object and that method accepts a constant as an argument with which it will scale each element in the array by and it will return you a new vector object that is scaled. I hope that makes sense.

here Dr Kahn has explained it, watch this video:
https://www.khanacademy.org/math/linear-algebra/vectors-and-spaces/vectors/v/multiplying-vector-by-scalar

whether you are using javascript map method or that c*x for x in self.coordinates… that python has… either way its basically doing the same thing.