Remove small trailing coefficients from a polynomial in Python

To remove small trailing coefficients from a polynomial, use the polynomial.polytrim() method in Python NumPy. The method returns a 1-d array with trailing zeros removed. If the resulting series would be empty, a series containing a single zero is returned.

The "Small" means "small in absolute value" and is controlled by the parameter tol; "trailing" means highest order coefficient(s). For example, in [0, 1, 1, 0, 0] (which represents 0 + x + x² + 0*x³ + 0*x?), both the 3rd and 4th order coefficients would be "trimmed". The parameter c is a 1-d array of coefficients, ordered from lowest order to highest. The parameter tol represents trailing (i.e., highest order) elements with absolute value less than or equal to tol that are removed.

Syntax

polyutils.trimcoef(c, tol=0)

Parameters:

  • c ? 1-d array of coefficients, ordered from lowest order to highest
  • tol ? Trailing elements with absolute value less than or equal to tol are removed (default: 0)

Basic Example

Let's create a polynomial array and remove trailing zeros ?

import numpy as np
from numpy.polynomial import polyutils as pu

# Create an array with trailing zeros
c = np.array([0, 5, 0, 0, 9, 0])
print("Original Array:", c)

# Remove trailing coefficients
result = pu.trimcoef(c)
print("After trimming:", result)
Original Array: [0 5 0 0 9 0]
After trimming: [0. 5. 0. 0. 9.]

Using Custom Tolerance

You can specify a tolerance value to remove small coefficients that are close to zero ?

import numpy as np
from numpy.polynomial import polyutils as pu

# Array with small trailing coefficients
coeffs = np.array([1.0, 2.0, 0.01, 0.001])
print("Original coefficients:", coeffs)

# Remove trailing coefficients smaller than 0.1
trimmed = pu.trimcoef(coeffs, tol=0.1)
print("Trimmed (tol=0.1):", trimmed)

# Remove trailing coefficients smaller than 0.01
trimmed2 = pu.trimcoef(coeffs, tol=0.01)
print("Trimmed (tol=0.01):", trimmed2)
Original coefficients: [1.    2.    0.01  0.001]
Trimmed (tol=0.1): [1. 2.]
Trimmed (tol=0.01): [1.   2.   0.01]

Edge Cases

When all coefficients are removed, the function returns an array with a single zero ?

import numpy as np
from numpy.polynomial import polyutils as pu

# Array with only small coefficients
small_coeffs = np.array([0.001, 0.002, 0.003])
print("Original:", small_coeffs)

# All coefficients removed with high tolerance
result = pu.trimcoef(small_coeffs, tol=0.01)
print("Result:", result)
print("Length:", len(result))
Original: [0.001 0.002 0.003]
Result: [0.]
Length: 1

Conclusion

The polyutils.trimcoef() function efficiently removes trailing coefficients from polynomial arrays based on a tolerance value. Use the default tolerance of 0 to remove only exact zeros, or specify a custom tolerance to remove small coefficients close to zero.

Updated on: 2026-03-26T19:41:39+05:30

329 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements