Skip to content

Instantly share code, notes, and snippets.

@grisaitis
Last active August 25, 2022 15:22
Show Gist options
  • Save grisaitis/572561ae83c8f54ae1f7cfa347dddf3d to your computer and use it in GitHub Desktop.
Save grisaitis/572561ae83c8f54ae1f7cfa347dddf3d to your computer and use it in GitHub Desktop.
Symbolic differentiation
from symdiff import Term, Polynomial
expression = "4x**3 - x"
polynomial = Polynomial.from_string(expression)
print("Polynomial:", polynomial)
print("Differentiated:", polynomial.differentiate())
class Term(object):
def __init__(self, coefficient, degree):
self.coefficient = float(coefficient)
self.degree = float(degree)
def __repr__(self):
return f'Term(coefficient={self.coefficient}, degree={self.degree})'
def __str__(self):
if not self.degree or not self.coefficient:
return f'{self.coefficient}'
if self.coefficient == 1:
coefficient_part = ''
elif self.coefficient == -1:
coefficient_part = '-'
else:
coefficient_part = self.coefficient
degree_part = 'x' if self.degree == 1 else f'x**{self.degree}'
return f'{coefficient_part}{degree_part}'
@classmethod
def from_string(cls, term_string):
try: # constant
return cls(coefficient=term_string, degree=0)
except ValueError:
coefficient, degree_info = term_string.split("x")
if coefficient == "": coefficient = 1
if coefficient == "-": coefficient = -1
# coefficient = 1 if coefficient == "" else -1 if coefficient == "-" else coefficient
try: # has an exponent
degree = degree_info.split("**").pop()
return cls(coefficient, degree=degree)
except: # degree 1
return cls(coefficient, degree=1)
def differentiate(self):
if self.degree == 0:
return Term(coefficient=0, degree=0)
else:
coefficient = self.coefficient * self.degree
degree = self.degree - 1
return Term(coefficient, degree)
class Polynomial(object):
def __init__(self, terms):
self.terms = terms
# or, omit zeros:
# self.terms = [t for t in terms if t is not None] or [Term(0, 0)]
def __repr__(self):
return f'Polynomial({repr(self.terms)})'
def __str__(self):
return " + ".join(str(t) for t in self.terms)
@classmethod
def from_string(cls, polynomial_string):
without_spaces = polynomial_string.replace(" ", "")
with_plus_signs = without_spaces.replace("-", "+-")
term_strings = [t for t in with_plus_signs.split("+") if t != ""]
terms = [Term.from_string(t) for t in term_strings]
return cls(terms)
def differentiate(self):
return Polynomial([t.differentiate() for t in self.terms])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment