Here I am computing the distance d between two points A and B and the
derivatives of d towards the coordinates of A and B
import sympy as sp
sp.init_printing()
X_A=sp.symbols('X_A')
Y_A=sp.symbols('Y_A')
Z_A=sp.symbols('Z_A')
X_B=sp.symbols('X_B')
Y_B=sp.symbols('Y_B')
Z_B=sp.symbols('Z_B')
d=sp.sqrt((X_A-X_B)**2+(Y_A-Y_B)**2+(Z_A-Z_B)**2)
Q=sp.Matrix([d])
R=sp.Matrix([X_A,Y_A,Z_A,X_B,Y_B,Z_B])
dQ_dR=Q.jacobian(R)
J=sp.MatrixSymbol('J',1,6)
print sp.fcode(dQ_dR,J)
This yields the (valid) code:
J(1, 1) = (X_A - X_B)/sqrt((X_A - X_B)**2 + (Y_A - Y_B)**2 + (Z_A
@ - Z_B)**2)
J(1, 2) = (Y_A - Y_B)/sqrt((X_A - X_B)**2 + (Y_A - Y_B)**2 + (Z_A
@ - Z_B)**2)
J(1, 3) = (Z_A - Z_B)/sqrt((X_A - X_B)**2 + (Y_A - Y_B)**2 + (Z_A
@ - Z_B)**2)
J(1, 4) = (-X_A + X_B)/sqrt((X_A - X_B)**2 + (Y_A - Y_B)**2 + (Z_A
@ - Z_B)**2)
J(1, 5) = (-Y_A + Y_B)/sqrt((X_A - X_B)**2 + (Y_A - Y_B)**2 + (Z_A
@ - Z_B)**2)
J(1, 6) = (-Z_A + Z_B)/sqrt((X_A - X_B)**2 + (Y_A - Y_B)**2 + (Z_A
@ - Z_B)**2)
unfortunately, this could have been written much more efficiently:
overd=1.0/sqrt((X_A - X_B)**2 + (Y_A - Y_B)**2 + (Z_A
@ - Z_B)**2)
J(1, 1) = (X_A - X_B)*overd
J(1, 2) = (Y_A - Y_B)*overd
J(1, 3) = (Z_A - Z_B)*overd
J(1, 4) = (-X_A + X_B)*overd
J(1, 5) = (-Y_A + Y_B)*overd
J(1, 6) = (-Z_A + Z_B)*overd
or even
J(1, 4) = -J(1,1)
J(1, 5) = -J(1,2)
J(1, 6) = -J(1,3)
Is there any way to have sympy recognise the possible use of such
"temporary variables", or if not, at least enforce when you specify them?
Would you expect compiler optimisation to catch this?
--
You received this message because you are subscribed to the Google Groups
"sympy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sympy.
To view this discussion on the web visit
https://groups.google.com/d/msgid/sympy/dad1a633-99b6-48dc-8507-bf96231d00d1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.