Getting Rid of the non-significant terms in symbolic equations in sympy


I am trying to obtain significant terms from a symbolic expression obtained using sympy.
The expressions represent symbolic dynamics of a a manipulator arm. The expression has the numerical coefficient always in the zeroth argument. However, the coefficients can be both positive and negative as seen in the expression for M. I want to eliminate the trigonometric terms associated with the coefficients which are insignificant such as – 1.38777878078145e-17 or 0.00044 which will have little impact on my overall computation and just consider the terms which are associated with coeeficient above certain threshold say threshold > 1e-4.

Below, I have attached a portion of the code:

import sympy
from sympy import symbols, sin, cos, parse_expr
import spatialmath.base.symbolic as sym

# Define the joint angles:
q = sym.symbol('q_:7')

M = - 0.105191*sin(q_2)**2*sin(q_3)**2*sin(q_4)**2 - 0.00044166666666667*sin(q_2)**2*sin(q_3)**2*sin(q_4)*sin(q_6)*cos(q_4)*cos(q_5)*cos(q_6) - 1.38777878078145e-17*sin(q_2)**2*sin(q_3)**2*sin(q_4)*cos(q_5) - 0.000441666666666671*sin(q_2)**2*sin(q_3)**2*sin(q_5)**2*sin(q_6)**2 - 0.170872*sin(q_2)**2*sin(q_3)**2*sin(q_5)**2 + 0.02756*sin(q_2)**2*sin(q_3)**2*sin(q_5)*cos(q_5) + 0.000220833333333334*sin(q_2)**2*sin(q_3)**2*sin(q_6)**2 + 0.085436*sin(q_2)**2*sin(q_3)**2

My progress:

I tried obtaining the significant terms using .as_coeff_mul() by considering the aruments of M as tuple, but it does not work.

signif_terms = [t for t in M.args if abs(t.as_coeff_mul()[0]) > 1e-4]

# Simplified Equation:
eqn_simp = M_00.func(*signif_terms)

Can anyone please help me with this?

Asked By: Anshul Nayak



For this particular case, one possible way is to use replace:

threshold = 1e-12
    lambda t: t.is_number, # select all numbers
    lambda t: 0 if abs(t) < threshold else t
Answered By: Davide_sd
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.