#!/usr/bin/env python
# coding: utf-8

# # Finite Differences vs Noise
# Copyright (C) 2020 Andreas Kloeckner
# 
# <details>
# <summary>MIT License</summary>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# </details>

# In[1]:


import numpy as np
import numpy.linalg as la
import matplotlib.pyplot as pt


# In[2]:


def f(x):
    return np.sin(2*x)
def df(x):
    return 2*np.cos(2*x)


# Here's a pretty simple function and its derivative:

# In[3]:


plot_x = np.linspace(-1, 1, 200)

pt.plot(plot_x, f(plot_x), label="f")
pt.plot(plot_x, df(plot_x), label="df/dx")
pt.grid()
pt.legend()


# Now what happens to our numerical differentiation if
# **our function values have a slight amount of error**?

# In[4]:


# set up grid
n = 10
x = np.linspace(-1, 1, n)
h = x[1] - x[0]
x_df_result = x[1:-1] # chop off first, last point

# evaluate f, perturb data, finite differences of f
f_x = f(x)

f_x += 0.025*np.random.randn(n)

df_num_x = (f_x[2:] - f_x[:-2])/(2*h)

# plot
pt.plot(x, f_x, "o-", label="f")
pt.plot(plot_x, df(plot_x), label="df/dx")
pt.plot(x_df_result, df_num_x, label="df/dx num")
pt.grid()
pt.legend(loc="best")


# * Now what happens if you set `n = 100` instead of `n = 10`?
