Skip to content

Instantly share code, notes, and snippets.

Created October 5, 2020 11:40
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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')
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])
label=f'Tangent {v_avg}')
v_avg = v_avg - diff * 2.0
print('new avg: ', v_avg)
plt.xlabel('average speed')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment