Planet Simulation In Python - Tutorial

Sdílet
Vložit
  • čas přidán 9. 06. 2024
  • Welcome back to another tutorial video! In this video I am going to be showing you how to make a planet simulation using Python! The goal of this tutorial is to simulate the orbits of different planets around the sun using real astronomical values! We're also going to apply the force of gravity on each of the planets so we get an accurate elliptical orbit! I hope you enjoy!
    💻 Thanks to BackTrace for sponsoring this video! Build better games with less bugs today for FREE by signing up for a developer account: hubs.la/Q012hTT00
    💻 ProgrammingExpert is the best platform to learn how to code and become a software engineer as fast as possible! Check it out here: programmingexpert.io/tim and use code "tim" for a discount!
    📄 Resources 📄
    Inspiration For This Video: fiftyexamples.readthedocs.io/...
    Code In This Video: github.com/techwithtim/Python...
    Fix Pip (Windows): • How to Install Pygame ...
    Fix Pip (Mac): www . • How to Install Pygame ...
    ⭐️ Timestamps ⭐️
    00:00 | Planet Simulation
    01:15 | Sponsor
    02:12 | Setup & Installation
    03:46 | Pygame Window Setup
    09:28 | Creating Planets
    18:50 | Initializing Planets (Using Real Values)
    27:33 | Moving Planets Explanation (Math & Physics)
    36:45 | Implementing Movement Physics
    51:58 | Drawing Orbits
    55:38 | Drawing Distance To Sun
    59:18 | Conclusion
    ◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
    👕 Merchandise: teespring.com/stores/tech-wit...
    📸 Instagram: / tech_with_tim
    📱 Twitter: / techwithtimm
    ⭐ Discord: / discord
    📝 LinkedIn: / tim-ruscica-82631b179
    🌎 Website: techwithtim.net
    📂 GitHub: github.com/techwithtim
    🔊 Podcast: anchor.fm/tech-with-tim
    🎬 My CZcams Gear: www.techwithtim.net/gear/
    💵 One-Time Donations: www.paypal.com/donate?hosted_...
    💰 Patreon: / techwithtim
    ◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
    ⭐️ Tags ⭐️
    -Tech With Tim
    -Planet Simulation
    -Planet Simluation In Python
    -How to Simulate Planets
    -Python Simulation Tutorial
    ⭐️ Hashtags ⭐️
    #TechWithTim #Python #PlanetSimulation

Komentáře • 439

  • @TechWithTim
    @TechWithTim  Před 2 lety +154

    Hey guys! Glad so many of you are enjoying this topic. Just wanted to note that I made a bunch of small physics/math errors in this video and I am by no means a physicist. Some people have politely pointed out the flaws in the simulation and that it is indeed a very rough approximation. Regardless, I think there is still a ton of value here and you can tweak/fix some parts to make it more accurate 👍

    • @randomdude7386
      @randomdude7386 Před 2 lety +18

      I dont think I could spot any major errors
      on either the maths or physics side in your explanations, but some times I as a physics major felt like you had no idea how to bring it accross as you seemed frightened of the possibility of saying something factually incorrect as the important part in this is, to bring the fundamental concept accross to those who came here not knowing how any of this worked.
      TLDR:
      Next time you do something like this, maybe try to be more relaxed and think less about the possibility of details being of in the grand scheme of things, as this has not stopped you from building this audience, as mistakes are human and it matters how we address them

    • @HypnosisBear
      @HypnosisBear Před 2 lety +5

      The thumbnail is click bait.😑 I thought you are gonna make a 3D simulation.

    • @mr.whiteboard6357
      @mr.whiteboard6357 Před 2 lety +1

      @@HypnosisBear Yeah me too

    • @Hiyouri005
      @Hiyouri005 Před 2 lety +1

      HEY CAN YOU POST CODE TOO//

    • @rafigasparyan6584
      @rafigasparyan6584 Před 2 lety +1

      @@Hiyouri005 the code, along with all of the resources he used and credited, are in the description (press SHOW MORE, the button is under the channel name and subscribe line/section).

  • @lissankoirala
    @lissankoirala Před 2 lety +252

    It's not the first time so pretty sure it's not just a coincidence. I was thinking about this project and here you go 3 days later posting the exact thing I want. You really seem to know what your audience needs, thanks Tim!

  • @renegadezed
    @renegadezed Před 2 lety +137

    f = ma .. NOT f = m/a .. force equals mass multiplied by acceleration

    • @TechWithTim
      @TechWithTim  Před 2 lety +63

      Great catch! Big brain fart from me

    • @renegadezed
      @renegadezed Před 2 lety +4

      @@TechWithTim no big deal! you still promote Kyte? that auto complete coding help thing?

    • @Mohd_Zaid_khan
      @Mohd_Zaid_khan Před rokem +16

      Funny thing is f ≠ ma, rather it's always dp/dt where p is linear momentum. for mass rate = 0, you can say net force along a line = mass multiplied by acceleration along that line

    • @jackyisking
      @jackyisking Před 5 měsíci +1

      But is gravity a force at all?

    • @youber3200
      @youber3200 Před 5 měsíci +1

      ​@jackyisking gravity is a field and gravitational force is a force :>

  • @vishsinghania
    @vishsinghania Před 2 lety +167

    amazing tutorial 👍
    just a correction at 45:00
    F = m times a (not m/a)

    • @joseph2073
      @joseph2073 Před 2 lety +3

      @Harsh 🤣

    • @hxdx6950
      @hxdx6950 Před 2 lety +1

      or F = Mg

    • @gillesphilippedeboissay109
      @gillesphilippedeboissay109 Před 2 lety +4

      @@hxdx6950 no it's true en Earth only sometimes

    • @Mickymauserius
      @Mickymauserius Před rokem +1

      But why does "self.x_vel += total_fx / self.mass * self.TIMESTEP" work. Shouldnt it be "self.x_vel += self.mass / total_fx * self.TIMESTEP"?

    • @rohan9739
      @rohan9739 Před rokem +2

      @@Mickymauserius The formula is F = m * a, so a = F / m ; therefore self.x_vel += total_fx / self.mass * self.TIMESTEP works

  • @kevinbacon8716
    @kevinbacon8716 Před 2 lety +3

    You’re about to hit a million subs. Congrats man. Your videos are great and as someone that’s new to python

  • @hyphenbruh7376
    @hyphenbruh7376 Před 2 lety +7

    That was awesome! I love and appreciate how you explained the logic behind each line of code and the concepts behind the physics of the orbits :D

  • @matheotrouille9085
    @matheotrouille9085 Před 2 lety +28

    Physics modeling is so interesting, look forward to see more like this !

  • @DevilisshDan
    @DevilisshDan Před 2 lety +68

    I think it's important to mention that what you're doing is just an approximate solution. When using the acceleration from the force and multiplying it with the timestep, you're taking a shortcut and calculating the average speed over a timestep. Since it's a many body problem, you can't get an "exact" solution.

    • @arkie87
      @arkie87 Před 2 lety +9

      yeah, it is also not energy conserving, as demonstrated when running without a vertical velocity component-- the planets just approached the sun and launched off to infinity.

    • @felicytatomaszewska2934
      @felicytatomaszewska2934 Před 2 lety +2

      We really look forward to your "exact solution"

    • @exar6765
      @exar6765 Před 2 lety +23

      @@felicytatomaszewska2934 He literally said : "You CAN'T get an exact solution". He's not saying it's a bad simulation, just an approximation

    • @mastershooter64
      @mastershooter64 Před 2 lety +4

      @@felicytatomaszewska2934 I think you can mathematically prove that it's impossible to get an analytic solution for a n-body problem

    • @aurelia8028
      @aurelia8028 Před 2 lety +3

      There's literally no other way to do it. I don't get what you mean by "shortcut". This method is forward euler integration, but yes there are more complex integration schemes like runge-kutta or verlet integration, but I don't think he knows anything about that

  • @danadasachan7208
    @danadasachan7208 Před 11 měsíci

    Thank Tim. I really enjoyed this project. I remember studying these planetary equations when I was in my undergraduate mechanical engineering program back in 1985 and I remember coding the orbit of a planet in Turbo Pascal. Crazy.

  • @emirhanu8655
    @emirhanu8655 Před 2 lety +4

    You are awesome, bro. Every time producing different ideas.. Keep going Tim

  • @nadeeshani
    @nadeeshani Před rokem

    You are amazing, Tim! Thank you so much for this project and for the way you explained it.

  • @universodacomputacao
    @universodacomputacao Před 11 měsíci

    This is so awesome that made me understand more about Space Engine, the best Universe Simulator that I've ever seen. Thank you so much

  • @amaarquadri
    @amaarquadri Před 2 lety +6

    Nice tutorial! The x and y variables are shadowing each other at you suspected at the end. The reason that it doesn't break the program is because x and y ended up being the last values in the orbit array, which happens to be the same.

  • @devbites77
    @devbites77 Před 2 lety +3

    Great! A fascinating simulation. I would love to see some more physics simulations using forces.

  • @NickHanson
    @NickHanson Před 4 měsíci

    This was a great introduction to the pygame library with a helpful foray into authentic simulation. Thank you for putting this together!

  • @annajuliagiza5916
    @annajuliagiza5916 Před 5 měsíci +1

    Thank you for the wonderful tutorial. You do an excellent job of showing and explaining each of the steps, what you're using in Python, and what each part of the program does. I just completed the CS50 Intro to Python course and was looking for a project to practice the skills taught. I have an avid interest in space so coming across this tutorial was excellent.

    • @_xiliam_7708
      @_xiliam_7708 Před 4 měsíci

      He did mistakes, but the idea and basic explanation is very good for the project

  • @xdaniels13
    @xdaniels13 Před 2 lety +8

    Awesome project Tim. I love physics and astronomy this is the perfect project to increase my skills in python :)

    • @_xiliam_7708
      @_xiliam_7708 Před 4 měsíci

      If u love physics how u didn't notice f= m/a? I don't even mean that his planets make rotation around the sun in 1 sec while timestep is only 1 day?

  • @googldeed
    @googldeed Před 2 lety

    I can finally get into data simulation now that you made the perfect introduction for me.

  • @bobmorone461
    @bobmorone461 Před 10 měsíci

    Five Star! Excellent. Thank you for providing detailed explanations as you are introducing the code. Simulations like this offer a good way to learn and provide a platform upon which to build more interesting simulations.

  • @phase0400
    @phase0400 Před rokem +4

    I would really enjoy seeing a 3D version of this.
    Nice video.

  • @Heisenberg_99101
    @Heisenberg_99101 Před 2 lety +36

    This is just pure level genius, great help for a python project. Loving it 🙌

  • @NishantCosmos
    @NishantCosmos Před 2 lety +1

    there's a great guy, explains the science behind planets in simplest way, claims we're confused
    like NO PROBLEM.

  • @flashypepo
    @flashypepo Před 2 měsíci

    Thanks, Tim. It is a very nice tutorial and introduction to astronomy, physics and Python, despite some minor flaws. I've made it, add the name of planet/sun to it and re-factored it in classes PlanetSimulation and Planet (which goes beyond your tutorial). It gave me a nice step up to go further in astronomy and astrophysics (when I was as young as you, I studied astronomy, years ago). kind regards, Peter.

  • @PayneMaximus
    @PayneMaximus Před 11 měsíci +17

    A more realistic simulation would be somewhat more complex than what you've done, since it would depend on the relative positions of each body and their velocities in a single instant, so you can use it as a starting point for the calculations.
    Still, good job! 😊

  • @lupamo_Arnold
    @lupamo_Arnold Před 2 lety

    Loved this project. Thanks Tim

  • @danielkursitis9031
    @danielkursitis9031 Před 2 lety +1

    Really enjoy this type of content, keep it up

  • @marcrindermann9482
    @marcrindermann9482 Před 2 lety +8

    when you want to express 1 AU in metres, just increase the exponent by 3: 1 AU = 149.6e9 metres; rather than 149.6e6 km × 1000 m/km

  • @yudianimations
    @yudianimations Před rokem

    great tutorial! thanks tim :D
    this also made me understand classes and stuff

  • @reubenthomas1033
    @reubenthomas1033 Před 2 lety +1

    Awesome! Please do more of these!

  • @DoctorSoulis
    @DoctorSoulis Před 2 lety

    Ty for the hard work. I learned a lot from this tutorial! :D

  • @martin-xq7te
    @martin-xq7te Před 2 lety

    Great tutorial Tim. Thankyou

  • @Ansh-Adonis
    @Ansh-Adonis Před 4 měsíci

    ill take this a step and a half further, thank you!

  • @Sk8erMorris
    @Sk8erMorris Před 2 lety +1

    ok this is sick, thanks for this one !

  • @domingezu4687
    @domingezu4687 Před 2 lety +1

    Very nice video TIM!

  • @jdefar3243
    @jdefar3243 Před 2 lety

    love you'r videos :D they are great I learn so much

  • @wowgodz-5349
    @wowgodz-5349 Před 2 lety +1

    ngl i've been waiting for this

  • @Greatbob-qu2ip
    @Greatbob-qu2ip Před 6 měsíci

    Coming from a physicist your explanation is by no means perfect but it's good enough for what you want to accomplish and that's more than enough keep up the good work

  • @J_GB
    @J_GB Před 2 lety

    this was awesome! very cool idea for a simulation

  • @toul100
    @toul100 Před 2 lety

    YOUR OPINION IS VALUED I LOVE THIS

  • @efschannel3043
    @efschannel3043 Před 2 lety +1

    Omg I was thinking about this for a long time

  • @shubhaggarwall
    @shubhaggarwall Před 2 lety

    well the thumbnail helped me revising the force formula thanksss

  • @Stl71
    @Stl71 Před 2 lety +1

    No surprise you have so many subscribers. Lots of interesting stuff in that channel, although I am not a python guy.

  • @quyennguyen6725
    @quyennguyen6725 Před 2 lety +2

    Honestly, I love videos like this. this is a 2d model, can you upgrade it to a 3d model. I look forward to it. Thank you for your contribution to the community.

  • @bvg129
    @bvg129 Před 2 lety +5

    You can use strings for common colors in pygame now. Since 2.0

  • @philosopherPsy
    @philosopherPsy Před 6 měsíci

    While watching your lecture, I immediately entered the code and tried it out on my computer.
    It is perfect and beautiful.
    You have been a great inspiration to me.
    I will also try Earth's satellite, the Moon, the asteroid belt and other large outer planets.
    It was a really fun weekend. Thank you!!!!

  • @satyadev2011
    @satyadev2011 Před 6 měsíci

    Great tut man.

  • @risveyhasan8931
    @risveyhasan8931 Před 2 lety

    Great work man.

  • @leonellg3167
    @leonellg3167 Před 2 měsíci

    The way the logic of the orbits is implemented means the orbit (and updated_points) lists will keep growing without end if the simulation is kept running.
    A slight modification to add a max number of points, and then an if statement to remove older points once the list has reached this max number would mean the simulation can run forever without issues.

  • @Burdiga_memes
    @Burdiga_memes Před 2 lety

    I really enjoyed the tutorial I am 12 years coder and I understood very thing eaisly thanks to you

  • @lissankoirala
    @lissankoirala Před 2 lety +6

    45:00 - you made an error here, F = m / a [supposed to be F = m*a]

  • @malibaturhan
    @malibaturhan Před 10 měsíci

    it was really satisfying even by copying you step by step, thank you

  • @timbeard8457
    @timbeard8457 Před 2 lety +3

    Super project! Have just bookmarked it for reference.
    Excellent that you included the interplanetary gravity too (from a coding and physics perspective). I agree that it was probably best not to use the general relativity description of gravity. The maths would have been hell! Newtonian physics was also good enough to get to the moon (I think)
    Questions:
    - Is there a way to only refresh / move just the changed items and not redraw everything? If there were lots of static objects, wouldn't that have a big performance impact? It would also mean that the complete history of the orbits wouldn't need redrawing each time, just the last point.
    - How would you approach having multiple sections in the app? Example: the canvas WIN on the left and some kind of control panel on the right for user input, plus a title / description area above both.
    - Would it be possible with pygame to dynamically change the window size, e.g. by the user grabbing the corner of the window?
    Please point me to any other videos or projects on GitHub you've done that address any of the points above.

  • @MilkenGamer42
    @MilkenGamer42 Před 2 lety

    This was a really fun tutorial to follow! I just started to learn Python and I found this video very informative. My problem with my code is that even though I was following this video, for some reason no matter what resolution I set the window, it would only do full screen and now windowed, so I'd have to hit window then X to close the program.
    You did an excellent job explaining how everything worked 😊

    • @itz_ronatime7527
      @itz_ronatime7527 Před 2 lety

      did u find a fix? my python doesnt run in windowed mode and its annoying..

  • @ConsultingjoeOnline
    @ConsultingjoeOnline Před 2 lety

    Amazing video. Freaking sweet!

  • @jessysavard2133
    @jessysavard2133 Před 2 lety

    your vid help me a lot no matter if some shit false, that give us something to fix and keep going lil watch and like every vid !

  • @Felix-wo7qz
    @Felix-wo7qz Před 2 lety

    cool tutorial, has been fun to program it!

  • @tusharpatel2003
    @tusharpatel2003 Před 2 lety +1

    It's amazing 😀🤩 bro
    Thank you for this ❤️

  • @vfx7t
    @vfx7t Před 2 lety +1

    Good job ! And thanks from Algeria !

  • @GregoryCarnegie
    @GregoryCarnegie Před 2 lety +3

    I played around with this and realised a slight simplification you can make.
    Since all objects feel the same acceleration regardless of their mass, you can write this script in terms of acceleration rather than force.
    e.g. velocity self.x_vel += total_ax * self.TIME_STEP

    • @aurelia8028
      @aurelia8028 Před 2 lety

      Yup using force is a rather "naive" way of doing it. division is also expensive for computers, so by calculating the acceleration directly, you can save the computer from doing quite a lot of unecessary work.

  • @gidartsproduction5439
    @gidartsproduction5439 Před 2 lety +1

    Wow, high quality information...

  • @GordonFreeman69
    @GordonFreeman69 Před 11 měsíci

    Thanks for the tutorial.

  • @user-yt6of5mt4c
    @user-yt6of5mt4c Před rokem +1

    amazing, you're really a genius

  • @chrisdanny5180
    @chrisdanny5180 Před 2 lety

    This is a brilliant idea

  • @muhammadmz8791
    @muhammadmz8791 Před rokem +1

    thank you tim 🙏

  • @feelsadgeman
    @feelsadgeman Před 2 lety +1

    I had the same idea, i was going to make this on my final project

  • @EarlWallaceNYC
    @EarlWallaceNYC Před 2 lety

    Thanks for the fun video. I was impressed that you included the planet-planet interactions.
    I wonder how long you can run this before the small errors kill it?

  • @antoine2571
    @antoine2571 Před 2 lety

    that's amazing, thank you

  • @ykslooper
    @ykslooper Před 2 lety

    i love you so much tim your videos are amazing. I hope you clsoe time you will 1 millon subs

  • @josephrios4437
    @josephrios4437 Před 2 lety

    awesome tutorial 👍

  • @RAMESHNEUPANE-jg2uu
    @RAMESHNEUPANE-jg2uu Před měsícem

    Great. Thank you.

  • @AstroBene
    @AstroBene Před 2 lety +1

    *sees the title, screams:* HELL YESS!
    Thanks!

  • @rverm1000
    @rverm1000 Před 2 lety

    wow that was good and hard. thanks!

  • @ayushmaanyadav4069
    @ayushmaanyadav4069 Před 2 lety +1

    I have my exams rn, i am gonna make this some day, probably gonna add a feature to see the simulation of objects around the planet, and also a feature to add an object in this system, like any object of a given mass, moving with a particular velocity in some direction. Gonna be difficult but can be done

  • @jdefar3243
    @jdefar3243 Před 2 lety +1

    fortunately i knew the math before hand otherwise this would be a lot harder ;D greate video

  • @unknownman5296
    @unknownman5296 Před 2 lety

    Thanks for the math lesson 👍

  • @si8915
    @si8915 Před 2 lety +2

    some day, tim will do "Filosophically Functional Life Forms In Python - Tutorial"

  • @absar_ahmad
    @absar_ahmad Před 2 lety +1

    This man have magical powers to know what we are thinking, believe me.

  • @norb3695
    @norb3695 Před 2 lety

    Hell yeah another Python tutorial 😃

  • @imen9464
    @imen9464 Před rokem

    Thanks a lot

  • @frankhaug1517
    @frankhaug1517 Před rokem

    15 minutes in. great video so far, i just hit all the buttons. however, you can do AU = 149.6e9 instead, same effect. edit: and since you mentioned consistency: 1*10**X = 1eX

  • @senaysew8231
    @senaysew8231 Před 2 lety

    It is really interesting!

  • @Totema.
    @Totema. Před 2 lety

    This is so nice 😮

  • @lamedev1342
    @lamedev1342 Před 2 lety

    Added a few new features to top off this project! I connected to a space api that displays people in space rn and also their names. Along with this users can watch planets move in slow mo.

  • @fun-damentals6354
    @fun-damentals6354 Před 5 měsíci +3

    this was a really informational video. to all new programmers, let me teach a way to partially escape tutorial hell. if you want to learn a language, but dont wanna worry about the logistics of a project, follow along with a tutorial in another language. i am learning c++, and it is about as far from python as it gets, and it helped me learn the language while still following along with the video

  • @saranyaghosh2003
    @saranyaghosh2003 Před 2 lety

    The title just drew me in!

  • @alexandermardis8179
    @alexandermardis8179 Před 2 lety

    Awesome ty!

  • @StarboyWithTech
    @StarboyWithTech Před 2 lety

    Really unexpected project like every Time 😉.

  • @lp2045
    @lp2045 Před 2 lety

    Now let's see uranus' simulation lol
    Great vid btw

  • @tiagosolano9728
    @tiagosolano9728 Před 6 měsíci

    Maybe someone already pointed this out, but the distance from the center of mass of the earth to astronauts in orbit IS NOT the reason why they do not experience the force of gravity.
    The reason is that they are on orbit around the earth, which is equivalent to being on free fall.
    Earth's gravitational field goes way beyond low earth orbit, as you can reason from the fact that the moon is in orbit around the earth at a far greater distance.

  • @techzenik
    @techzenik Před 2 lety

    Awesome!!!

  • @ANNGUYEN-cw7lw
    @ANNGUYEN-cw7lw Před 9 měsíci

    Your tutorial is very awesome. I hope you will create many other tutorial in the future ?.

  • @petruthegamer9777
    @petruthegamer9777 Před 2 lety

    Thanks.

  • @TAP7a
    @TAP7a Před 2 lety

    Skip involving trigonometry, do it all component by component!
    Force_x = (other.x - self.x) * Planet.G * self.mass * other.mass / distance ** 3
    Force_y = (other.y - self.y) * Planet.G * self.mass * other.mass / distance ** 3
    No need for expensive atan calcs, just needs another 2 factors to multiply!
    Also would recommend either Verlet or RK-4 integration schemes rather than Euler ;)

  • @jakovbilic4556
    @jakovbilic4556 Před 2 lety

    Superb!

  • @LDR_Crafts
    @LDR_Crafts Před 4 měsíci

    :. F = mv²/r in circular motion.. So you can actually find the velocity of an object.
    Hence - v = √(rF/m) 😊

  • @novidtoshow
    @novidtoshow Před měsícem

    Just a little nit: the gravitational force weakens as the inverse square of the distance. It doesn't weaken "exponentially". The word, "exponentially", has a very specific mathematical meaning. You're gonna want to have that meaning available to you one day when you really need it.

  • @thatego9417
    @thatego9417 Před 2 lety

    hey can you make a tutorial on using pyglet ,pygam ,numpy or sympy , to create some physics model ?like cars crashing , or a pulley system with weights and stuff.

  • @spaceflight
    @spaceflight Před 2 lety +1

    very cool

  • @lucidjuice101
    @lucidjuice101 Před 5 měsíci

    The reason why the value of y_vel of venus is negative is because of the fact that venus' orbit is titled to 180 degrees. So unlike all other planets, it orbits clockwise around the sun.

  • @1803harshi0033
    @1803harshi0033 Před rokem

    Hey Tim, I enjoyed the video, one query .. instead of color is it possible to use the images of the planets..