Skip to content

Instantly share code, notes, and snippets.

@aidenfoxivey
Created April 8, 2023 17:22
Show Gist options
  • Save aidenfoxivey/9ffb24977b5bc1feb748fc6693439b41 to your computer and use it in GitHub Desktop.
Save aidenfoxivey/9ffb24977b5bc1feb748fc6693439b41 to your computer and use it in GitHub Desktop.
Symbolic Differentiation in Python
# I've left this here in case we want to implement diff for trig or other functions
class Function:
def __init__(self):
pass
def diff(self):
pass
class Polynomial(Function):
def __init__(self, coeffs):
# coeffs should be passed in highest order (e.g. x^7) to the lowest
self._coeffs = coeffs
# remove the leading zeroes
while self._coeffs[0] == 0:
self._coeffs.pop(0)
self._degree = len(coeffs) - 1
# evaluate the polynomial using Horner's method
# (not the super optimized version)
def eval(self, x):
i = 1
acc = self._coeffs[0]
while i < self._degree+1:
acc = self._coeffs[i] + x * acc
i += 1
return acc
# one optional improvement could be not printing the leading 1
# (e.g. 1x^2 + 3x + 4) --> (x^2 + 3x + 4)
# another optional improvement could be not printing terms with a 0 coefficient
# (e.g. 1x^2 + 0x + 4) --> (x^2 + 4)
def __str__(self):
pretty_str = ""
i = 0
while i < self._degree:
if (self._degree - i) == 1:
pretty_str += f"{self._coeffs[i]}x + "
else:
pretty_str += f"{self._coeffs[i]}x^{self._degree - i} + "
i += 1
pretty_str += f"{self._coeffs[self._degree]}"
return pretty_str
def diff(self):
for i in range(self._degree):
self._coeffs[i] *= (self._degree - i)
self._degree -= 1
if __name__ == "__main__":
f = Polynomial([0, 5, 3, 2])
print(f)
print(f.eval(5))
print(f._degree)
print()
f.diff()
print(f)
print(f.eval(5))
print(f._degree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment