# -*- coding: utf-8 -*-
"""
Created on Mon Aug  1 14:15:47 2022

@author: Chris

Lab 1 Question 8 - numerical forward derivative
"""
import numpy as np
import matplotlib.pyplot as plt

"""
Function definitions
"""

def myfun(x):
    myfun = np.sin(x)**2
    return myfun


""" Main Script starts"""

h = np.logspace(-14,-1,100)    # choose range of steps

xrange = [0.1,0.5, 1.0, 1.5]

for x in xrange:
    dfdx = (myfun(x+h)-myfun(x))/h #numerical derivative
    dfdx_real = 2*np.sin(x)*np.cos(x) #analytic solution
    
    err_abs = abs(dfdx-dfdx_real) #absolute error
    err_rel = err_abs/dfdx_real   #relative error
    
#    plt.loglog(h,err_abs,'.') # plot absolute error
    plt.loglog(h,err_rel,'.') # plot relative error
    
    plt.xlabel('stepsize h')
    plt.show()
    input()

    






