{ "cells": [ { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" } }, "source": [ "# Exercise: Add the function `update_position` to the `Particle` class\n", "\n", "- Make the function `update_position` into a method of the class `Particle`\n", "- Where do the position `position` of the particle belong? Modify the class constructor if necessary\n", "- Once it is done, create a particle with mass 2.1 with velocity 0.8 at position 8.2 . Update the position with dt=0.1 and print out the new location." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2018-07-27T15:05:51.531289Z", "start_time": "2018-07-27T17:05:51.526519+02:00" }, "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [ "def update_position(velocity, position, dt):\n", " return position + velocity * dt" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.6800000000000002\n" ] } ], "source": [ "class Particle:\n", " def __init__(self, mass, velocity, position):\n", " self.mass = mass\n", " self.velocity = velocity\n", " self.position = position\n", "\n", " def momentum(self):\n", " return self.mass * self.velocity\n", "\n", " def update_position(self, dt):\n", " self.position = self.position + self.velocity * dt\n", " return self.position\n", "\n", "particle = Particle(mass=2.1, velocity=0.8)\n", "print(particle.momentum())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8.28\n" ] } ], "source": [ "position = 8.2\n", "particle = Particle(2.1, 0.8, position)\n", "new_position = particle.update_position(dt=0.1)\n", "print(new_position)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "pycharm": { "name": "#%%\n" } }, "outputs": [], "source": [] } ], "metadata": { "hide_input": false, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.11" }, "toc": { "nav_menu": { "height": "174px", "width": "252px" }, "navigate_menu": true, "number_sections": true, "sideBar": true, "threshold": 4, "toc_cell": false, "toc_position": { "height": "953px", "left": "0px", "right": "1253px", "top": "127px", "width": "320px" }, "toc_section_display": "block", "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 2 }