Created
August 21, 2019 23:00
-
-
Save Nikolaj-K/ee0b81295abb86817331af3e3212d42f to your computer and use it in GitHub Desktop.
Implementing polynomials as arrays, evaluating them and taking their derivatives.
This file contains hidden or 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
class VirtualMachine: | |
def __init__(self, update_step, max_num_updates=0, halting_condition=lambda state: False): | |
self.update_step = update_step | |
self.halting_condition = halting_condition | |
self.max_num_updates = max_num_updates | |
self.num_updates = 0 | |
def run(self, state): | |
halt = False | |
while(not halt): | |
state = self.update_step(state) | |
self.num_updates += 1 | |
halt = self.halting_condition(state) or self.num_updates == self.max_num_updates | |
return state | |
def pretty_print(name, cs, x): | |
name_string = "{}({})".format(name, x) | |
terms_string = " + ".join("({} * {}^{})".format(c_n, x, n) for n, c_n in enumerate(cs)) | |
print("{} = {}".format(name_string, terms_string)) | |
def evaluate(cs, x): | |
return sum(c_n * x**n for n, c_n in enumerate(cs)) | |
def derivative(name, cs): | |
return [0] if len(cs)==1 else [c_n * n for n, c_n in enumerate(cs) if n > 0] | |
def update_step(state): | |
state['loop_counter'] += 1 | |
name = "p" + "'" * state['loop_counter'] | |
state['cs'] = derivative(name, state['cs']) | |
pretty_print(name, state['cs'], 'X') | |
return state | |
if __name__ == "__main__": | |
CS = [2, 0, -9, 3] | |
pretty_print("p", CS, "X") | |
X = 80 | |
pX = evaluate(CS, X) | |
print("p({}) = {}".format(X, pX), "\n") | |
state = dict(cs=CS, loop_counter=0) | |
vm = VirtualMachine(update_step, max_num_updates=6) | |
vm.run(state) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment