
# calcExp.py

import math
from frange import *
import matplotlib.pyplot as plt

import decimal
from decimal import Decimal as D

def calcExp(x):
  n = 0
  oldsum, tot, term = 0, 1, 1
  while tot != oldsum:
    oldsum = tot
    n += 1
    term *= x/n
    tot += term
    # tot += (x**n)/math.factorial(n)
  print(n, "iterations")
  return tot

# --------------------------------

if __name__ == "__main__":
  print("Decimal context:", decimal.getcontext())
  decimal.getcontext().prec = 100
  
  
  xs = list(frange(0, 30, 0.1))
  ys = []
  for x in xs:
    ys.append( (calcExp(x) - math.exp(x))/math.exp(x) )
    # ys.append( (calcExp(D(x)) - D(x).exp())/D(x).exp() )
  
  plt.xlabel("x")
  plt.ylabel("error")
  plt.plot(xs, ys)
  
  plt.title("Relative Diff Errors for exp()s")
  plt.show()
