|
| 1 | +""" |
| 2 | +Find the kinetic energy of an object, give its mass and velocity |
| 3 | +Description : In physics, the kinetic energy of an object is the energy that it |
| 4 | +possesses due to its motion. It is defined as the work needed to accelerate a body of a |
| 5 | +given mass from rest to its stated velocity. Having gained this energy during its |
| 6 | +acceleration, the body maintains this kinetic energy unless its speed changes. The same |
| 7 | +amount of work is done by the body when decelerating from its current speed to a state |
| 8 | +of rest. Formally, a kinetic energy is any term in a system's Lagrangian which includes |
| 9 | +a derivative with respect to time. |
| 10 | +
|
| 11 | +In classical mechanics, the kinetic energy of a non-rotating object of mass m traveling |
| 12 | +at a speed v is ½mv². In relativistic mechanics, this is a good approximation only when |
| 13 | +v is much less than the speed of light. The standard unit of kinetic energy is the |
| 14 | +joule, while the English unit of kinetic energy is the foot-pound. |
| 15 | +
|
| 16 | +Reference : https://en.m.wikipedia.org/wiki/Kinetic_energy |
| 17 | +""" |
| 18 | + |
| 19 | + |
| 20 | +def kinetic_energy(mass: float, velocity: float) -> float: |
| 21 | + """ |
| 22 | + The kinetic energy of a non-rotating object of mass m traveling at a speed v is ½mv² |
| 23 | +
|
| 24 | + >>> kinetic_energy(10,10) |
| 25 | + 500.0 |
| 26 | + >>> kinetic_energy(0,10) |
| 27 | + 0.0 |
| 28 | + >>> kinetic_energy(10,0) |
| 29 | + 0.0 |
| 30 | + >>> kinetic_energy(20,-20) |
| 31 | + 4000.0 |
| 32 | + >>> kinetic_energy(0,0) |
| 33 | + 0.0 |
| 34 | + >>> kinetic_energy(2,2) |
| 35 | + 4.0 |
| 36 | + >>> kinetic_energy(100,100) |
| 37 | + 500000.0 |
| 38 | + """ |
| 39 | + if mass < 0: |
| 40 | + raise ValueError("The mass of a body cannot be negative") |
| 41 | + return 0.5 * mass * abs(velocity) * abs(velocity) |
| 42 | + |
| 43 | + |
| 44 | +if __name__ == "__main__": |
| 45 | + import doctest |
| 46 | + |
| 47 | + doctest.testmod(verbose=True) |
0 commit comments