Skip to content

Instantly share code, notes, and snippets.

@xmodar
Created September 10, 2019 01:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xmodar/1d3b3c2615f25ac29ba83748613f9064 to your computer and use it in GitHub Desktop.
Save xmodar/1d3b3c2615f25ac29ba83748613f9064 to your computer and use it in GitHub Desktop.
Compute polynomials efficiently with numpy and pytorch (differentiable).
import torch
def polynomial(coefficients, x):
"""Evaluate polynomials using Horner method.
The coefficients are from highest to lowest order.
Args:
coefficients: Tensor of size (N, *K).
K is any broadcastable size to `x.size()`.
x: Arbitrary tensor.
Returns:
The evaluated polynomial at `x` with the same size.
"""
out = x.new_zeros(x.size()) if torch.is_tensor(x) else 0
coefficients = iter(coefficients)
out += next(coefficients, 0)
for c in coefficients:
out *= x
out += c
return out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment