This repository has been archived on 2021-05-17. You can view files and clone it, but cannot push or open issues or pull requests.
scientificComputing/regression/lecture/derivative.py

55 lines
1.4 KiB
Python

import numpy as np
import matplotlib.pyplot as plt
from plotstyle import *
plain_style()
fig, ax = plt.subplots(figsize=(2.5,3.4))
# parabula:
x1 = -0.2
x2 = 0.9
x = np.linspace(x1, x2, 200)
y = x*x
ax.set_xlim(x1, x2)
ax.set_ylim(-0.2, 0.7)
ax.plot(x, y, zorder=0, **lsA)
# secant:
x = np.asarray([0.1, 0.7])
y = x*x
ax.set_xticks(x)
ax.set_yticks(y)
ax.set_xticklabels(['$x$','$x+\Delta x$'])
ax.set_yticklabels(['',''])
ax.plot(x, y, zorder=10, **psB)
# function values:
ax.plot([x[0], x[0], x1],[-0.2, y[0], y[0]], zorder=6, **lsGrid)
ax.plot([x[1], x[1], x1],[-0.2, y[1], y[1]], zorder=6, **lsGrid)
ax.text(x1+0.05, y[0]+0.05, '$f(x)$', zorder=6)
ax.text(x1+0.05, y[1]+0.05, '$f(x+\Delta x)$', zorder=6)
# slope triangle:
ax.plot([x[0], x[1], x[1]],[y[0], y[0], y[1]], zorder=7, **lsMarker)
ax.text(np.mean(x), y[0]-0.07, '$\Delta x$', ha='center', zorder=7)
ax.text(x[1]+0.05, np.mean(y), '$f(x+\Delta x)-f(x)$', va='center', rotation='vertical', zorder=7)
# secant line:
m = np.diff(y)/np.diff(x)
xl = [x1, x2]
yl = m*(xl-x[0])+y[0]
ax.plot(xl, yl, zorder=7, **lsBm)
# derivative:
md = 2.0*x[0]
yl = md*(xl-x[0])+y[0]
ax.plot(xl, yl, zorder=5, **lsDm)
# limit:
for ml in np.linspace(md, m, 5)[1:] :
yl = ml*(xl-x[0])+y[0]
xs = 0.5*(ml+np.sqrt(ml*ml-4.0*(ml*x[0]-y[0])))
ax.plot([xs], [xs*xs], zorder=3, **psC)
ax.plot(xl, yl, zorder=3, **lsCm)
fig.subplots_adjust(**adjust_fs(fig, 0.5, 0.5, 1.4, 0.5))
plt.savefig('derivative.pdf')
#plt.show();