Created
March 21, 2013 00:24
-
-
Save tapichu/5209739 to your computer and use it in GitHub Desktop.
Calculate polynomials and their derivatives
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
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