Instantly share code, notes, and snippets.

# kayhman/descent_dp.py

Created October 5, 2020 11:40
Star You must be signed in to star a gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 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()