Skip to content

Instantly share code, notes, and snippets.

@kayhman
Created October 5, 2020 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kayhman/fbb275947c2eca5983035be211164f15 to your computer and use it in GitHub Desktop.
Save kayhman/fbb275947c2eca5983035be211164f15 to your computer and use it in GitHub Desktop.
import matplotlib.pyplot as plt
import numpy as np
from forward_autodiff import DualFloat
trip_distance = DualFloat(6.0) # km
trip_duration = DualFloat(12.0) # minutes
trip_avg_speed = DualFloat(30.0) # km/h
# trip duration in minutes
def duration(distance, speed):
return DualFloat(60.0, 0) * distance / speed
def speed_error(speed):
dur = duration(trip_distance, speed)
return trip_duration - dur
speeds = np.vectorize(DualFloat)(np.linspace(20, 50))
error = np.vectorize(speed_error)(speeds)
squared_error = error**2
fig, ax = plt.subplots()
ax.grid(True, which='both')
ax.plot(np.vectorize(float)(speeds),
np.vectorize(float)(squared_error),
label='Squared error wrt to speed param')
v_avg = DualFloat(35, 1.0)
for i in range(0,7):
error = speed_error(v_avg)**2
diff = error.derivative()
tangente = (speeds - v_avg) * diff + speed_error(v_avg)**2
ax.scatter([trip_avg_speed, v_avg], [0, speed_error(v_avg)**2])
ax.plot(np.vectorize(float)(speeds),
tangente,
label=f'Tangent {v_avg}')
v_avg = v_avg - diff * 2.0
print('new avg: ', v_avg)
plt.xlabel('average speed')
plt.legend()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment