Calculus I for Programmers

Average speed on the ramp

Average speed on the ramp

A ball is released at the top of a ramp and a sensor records how far it has gone. After t seconds it has travelled 3 * t * t metres. A physics class wants a small tool that answers one question: over the h seconds starting at time t, how fast was the ball going on average?

Write a function called ramp_speed that takes the starting time t and the length of the interval h, both in seconds, and returns the average speed over that interval in metres per second. That is the distance covered divided by the time taken.

The interval may run backwards. If h is negative, the interval is the h seconds ending at t, and the same formula still gives the right answer, because the rise and the run both change sign.

Worked example

Input:  t = 2, h = 1
Output: 15

At t = 2 the ball has gone 3 * 2 * 2 = 12 metres.
At t = 3 the ball has gone 3 * 3 * 3 = 27 metres.
That is 15 metres in 1 second, so 15 metres per second.
Input:  t = 5, h = 0.1
Output: 30.3

At t = 5.0 the ball has gone 75 metres.
At t = 5.1 the ball has gone 78.03 metres.
That is 3.03 metres in 0.1 seconds, so 30.3 metres per second.

Constraints

  • t is between 0 and 20.
  • h is between -1 and 1, and is never 0.
  • Answers are compared with a tolerance, since this one is a decimal.
Code

Run your code to see how it does on the examples. Submit also runs the hidden cases.