# horner.py
'''
Introduction to Programming in Python
Robert Sedgewick, Kevin Wayne, Robert Dondero
Addison-Wesley, 2015
Ex 2.2.1.29 Homer’s method
https://introcs.cs.princeton.edu/python/21function/
'''

# Use the Horner method to compute n terms
# of the Taylor series e^x = 1 + x + x^2/2! + .... 

# inputs: 30 0.7

import math


def hornerEval(x, a):
  '''
  Use Horner's method to compute and return the polynomial
     a[0] + a[1] x^1 + a[2] x^2 + ... + a[n-1] x^(n-1)
  evaluated at x.
  '''
  result = 0
  for i in range(len(a)-1, -1, -1):
    result = a[i] + (x * result)
  return result



n = int(input("n=? "))


# Compute coefs for Taylor series
# e^x = 1 + x + x^2/2! + x^3/3! + ...
a = [0]*n
a[0] = 1.0
for i in range(1, n):
    a[i] = a[i-1] / float(i)

# Evaluate the polynomial at x
x = float(input("x=? "))

print("Horner exp():", hornerEval(x, a))
print("Math exp():  ", math.exp(x))
