Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sympy - dot product and norm of symbolic vector

Tags:

python

sympy

Is there a way to express an symbolic expression involving vectors and operations on them without evaluating them?

from sympy import symbols, acos, MatrixSymbol, Matrix

rA = MatrixSymbol("r^A", 2, 1)
rB = MatrixSymbol("r^B", 2, 1)
rA, rB = Matrix(rA), Matrix(rB) # Basically I want to skip this step
acos((rA.dot(rB)) / rA.norm())

This will evaluate the expression to:

    ⎛r_00__A⋅r_00__B + r_10__A⋅r_10__B ⎞ 
acos⎜─────────────────────────────────⎟
    ⎜      _________________________  ⎟
    ⎜     ╱          2            2   ⎟
    ⎝   ╲╱  │r_00__A│  + │r_10__A│    ⎠

But instead I would like it to evaluate to something like this, while still being able to substitute the symbolic Vectors later on.

    ⎛ r_A⋅r_B ⎞
acos⎜─────────⎟
    ⎝ ||r_A|| ⎠
like image 285
pask Avatar asked Mar 19 '19 09:03

pask


People also ask

How do I normalize a vector in SymPy?

You'll just have to use the equation Eq(v. norm(), 1) in some way, at whatever step of computations requires using the information that v is a unit vector. It's probably easier for SymPy to use the equation in the form Eq(v. norm()**2, 1) , without the square root.

How do you evaluate a SymPy expression?

To evaluate a numerical expression into a floating point number, use evalf . SymPy can evaluate floating point expressions to arbitrary precision. By default, 15 digits of precision are used, but you can pass any number as the argument to evalf .

How do you write an ex in SymPy?

Note that by default in SymPy the base of the natural logarithm is E (capital E ). That is, exp(x) is the same as E**x .

How do you find the transpose of a matrix in SymPy?

To actually compute the transpose, use the transpose() function, or the . T attribute of matrices. Represents the trace of a matrix expression.


1 Answers

You could replace .dot and .norm by matrix product : acos(A.T*B/sqrt(A.T*A)).
Minimal working example :

In [1]: from sympy import *
In [2]: init_printing(use_unicode=True)
In [3]: init_printing(use_latex=False)
In [4]: A = MatrixSymbol('A', 2, 1)
In [5]: B = MatrixSymbol('B', 2, 1)
In [6]: acos(A.T*B/sqrt(A.T*A))
Out[6]: 
    ⎛           -1/2⎞
    ⎜ T   ⎛ T  ⎞    ⎟
acos⎝A ⋅B⋅⎝A ⋅A⎠    ⎠
like image 81
LaurentValade Avatar answered Sep 28 '22 05:09

LaurentValade