Skip to content

Instantly share code, notes, and snippets.

@tapichu
Created March 21, 2013 00:24
Show Gist options
  • Save tapichu/5209739 to your computer and use it in GitHub Desktop.
Save tapichu/5209739 to your computer and use it in GitHub Desktop.
Calculate polynomials and their derivatives
from itertools import imap
def polynomial(coefs, x):
"""computes the value of a polynomial with
the given coefficients for a given value x"""
# For example, if coefs contains 3 values then exponents is [2 1 0]
exponents = reversed(range(len(coefs)))
return sum(map(lambda c,e: c * x**e, coefs, exponents))
def derivative(coefs, x):
"""computes the value of the derivative of a polynomial
with the given coefficients for a given value x"""
# The coefficients of the derivative function are obtained by
# multiplying all but the last coefficient by its corresponding exponent.
# The extra exponent will be ignored.
exponents = reversed(range(len(coefs)))
derivative_coefs = list(imap(lambda c,e: c*e, coefs[:-1], exponents))
return polynomial(derivative_coefs, x)
f = lambda x: polynomial([2, 1, 3], x) # 2x^2 + x + 3
f_prime = lambda x: derivative([2, 1, 3], x) # 4x + 1
print "f(2) = ", f(2) # --> 13
print "f'(2) = ", f_prime(2) # --> 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment