fork download
  1. import numpy as np
  2. from scipy.optimize import minimize
  3. import math
  4.  
  5. def total_travel_time(d):
  6. """
  7. Given an array d of 7 horizontal displacements (in leagues) for each segment,
  8. compute the total travel time.
  9.  
  10. Each segment has a fixed vertical distance of 10 leagues. The travel distance in
  11. segment i is L_i = sqrt(d_i^2 + 10^2). The speeds for the 7 segments are:
  12. v0 = 10, v1 = 9, v2 = 8, v3 = 7, v4 = 6, v5 = 5, v6 = 10 (leagues/day).
  13.  
  14. The total time is:
  15. T = sum_{i=0}^{6} L_i / v_i.
  16. """
  17. speeds = [10, 9, 8, 7, 6, 5, 10]
  18. T = 0.0
  19. for i in range(7):
  20. L = math.sqrt(d[i]**2 + 10**2)
  21. T += L / speeds[i]
  22. return T
  23.  
  24. def constraint_sum(d):
  25. """Constraint: sum of horizontal displacements must equal 100 leagues."""
  26. return np.sum(d) - 100
  27.  
  28. # Initial guess: equally distribute 100 leagues among 7 segments.
  29. d0 = np.full(7, 100/7)
  30.  
  31. # Set up the equality constraint and bounds (each d_i must be nonnegative)
  32. cons = {'type': 'eq', 'fun': constraint_sum}
  33. bnds = [(0, None) for _ in range(7)]
  34.  
  35. # Use SLSQP to minimize the total travel time
  36. res = minimize(total_travel_time, d0, method='SLSQP', bounds=bnds, constraints=cons, options={'ftol': 1e-12})
  37.  
  38. if res.success:
  39. optimal_d = res.x
  40. T_opt = res.fun
  41. # Recover the cumulative horizontal x–positions: x0 = 0, then x_i = sum_{j=1}^i d_j, and x7 = 100.
  42. x_positions = np.concatenate(([0], np.cumsum(optimal_d), [100]))
  43.  
  44. print("Optimal horizontal displacements d_i (leagues):")
  45. print(optimal_d)
  46. print("\nCumulative x–positions:")
  47. print(x_positions)
  48. print("\nMinimum travel time = {:.13f} days".format(T_opt))
  49. else:
  50. print("Optimization did not converge.")
Success #stdin #stdout 1.62s 63292KB
stdin
Standard input is empty
stdout
Optimal horizontal displacements d_i (leagues):
[26.24703292 15.54595739 11.25579302  8.64818992  6.7713027   5.28470241
 26.24702164]

Cumulative x–positions:
[  0.          26.24703292  41.79299031  53.04878333  61.69697324
  68.46827595  73.75297836 100.         100.        ]

Minimum travel time = 15.7169800163289 days