Created
September 10, 2019 01:40
-
-
Save xmodar/1d3b3c2615f25ac29ba83748613f9064 to your computer and use it in GitHub Desktop.
Compute polynomials efficiently with numpy and pytorch (differentiable).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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