Rudolf Adamkovič Personal site


Example: Vector and graph

Given y=sinx, graph y and dy/dx at x[π,π].

import math
import tensorflow as tf
import matplotlib.pyplot as plt

# Differentiate.

x = tf.linspace(-math.pi, math.pi, 100)

with tf.GradientTape() as tape:
    tape.watch(x)
    y = tf.sin(x)

dy_dx = tape.gradient(y, x)

# Plot.

plt.style.use('dark_background')
plt.rc('legend', facecolor='#111')

fig, ax = plt.subplots()

ax.set_xlabel(r'\(x\)')
ax.set_xticks([-math.pi, 0, +math.pi])
ax.set_xticklabels([r'\(-\pi\)', '0', r'\(\pi\)'])

ax.set_ylabel(r'\(y\)')
ax.set_yticks([-1, 0, +1])

ax.plot(x, y, label=r'\(y = \sin(x)\)')
ax.plot(x, dy_dx, label=r'\(y = \dv*{x} \sin(x) = \cos(x)\)')

ax.grid()
ax.legend()

fig
svg/fb886e3f-7bf8-4ddb-957b-3bf2495ca3fd

© 2025 Rudolf Adamkovič under GNU General Public License version 3.
Made with Emacs and secret alien technologies of yesteryear.