Jaime02
Jaime02

Reputation: 347

How do I calculate a scalar product in a sympy vector?

Pretty simple question:

from sympy.vector import Vector
v = Vector(0, 2, 1)
print(2*v)

Output expected: Vector(0, 4, 2)

I'm unable to find how to do this, the docs do not talk about scalar product.

Upvotes: 0

Views: 413

Answers (2)

smichr
smichr

Reputation: 18939

Matrix understands scalar multiplication but not Vector. So either convert back and forth between Matrix and Vector, file a feature request and wait for a possible enhancement, or write your own __mul__ and __rmul__ routine (part of the beauty of Python):

>>> v.func(*Matrix(v.args)*2)
Vector(0, 4, 2)
>>> Vector.__rmul__ = Vector.__mul__ = lambda s,o: s.func(*[i*o for i in s.args])
>>> 2*v
Vector(0, 4, 2)
>>> v*2
Vector(0, 4, 2)

Upvotes: 1

Oscar Benjamin
Oscar Benjamin

Reputation: 14470

I think the expected way to work with vectors is to create a coordinate system and use its i, j, k basis:

In [32]: from sympy.vector import CoordSys3D                                                                                                   

In [33]: N = CoordSys3D('N')                                                                                                                   

In [34]: v = 2*N.j + N.k                                                                                                                       

In [35]: v                                                                                                                                     
Out[35]: 2*N.j + N.k

In [36]: 2*v                                                                                                                                   
Out[36]: 4*N.j + 2*N.k

Upvotes: 1

Related Questions