Fun fact in case nobody else has mentioned it: updating the positions using the "current velocity" vs the previous one changes the numerical method from Euler's method to the Euler-Cromer method, which is quite a lot more accurate. The regular Euler method is prone to inadvertently increasing the energy of the system, while the Euler-Cromer method conserves energy quite decently. The two methods seem almost identical, but the behind the scenes math is quite interesting and shows that they are actually of different orders.
To those who want to make this simulation more real do this. Currently Dan is setting g = 1. Although its far from the actual value the simulation looks very real. This is because one second in the simulation is one frame. And by default processing or p5.js is set to 60 fps. This means when one second passes in real world, 60 seconds would have passed in the simulation world. Hence the correct value of g would be 9.8/ ( 60 * 60 ) . There's still one more thing to adjust. The masses are actually in kilograms hence you should set the value of bob masses to around 0.05 which is 50 grams. Also, the lengths are in meters so make that they aren't very large.
This Guy has made a magic. But when we give the real numbers within no time, the software is getting into errors. he has very intelligently demonstrated the capabilities given the limitation of a 30 min video. The world appreciated him for this.
João Vitor Bonadiman Same... When I noticed the video would end soon from the way he talked I looked up the runtime because I hoped there was more to come with messing with the values. Then I noticed I've watched 30 min of coding feeling like 5...
Missing Semicolon I died. Small g is acceleration of gravity on earth = 9.81 m/s^2. Big G is the universal gravitational constant, 6.67 x 10^-11. TRIGGERED!!!
Top comment!! This explains your astute observation at 23:33 "It's got quite a bounce to it." The simple/forward Euler method tends to artificially add energy to this system, while the symplectic/semi-implicit Euler method is better at conserving energy. There are many other variant methods, including the so-called midpoint method (angle is updated by the average of present and future velocity steps).
I think a cool feature to add would be a fade of the trace line, so as a segment of line is drawn, say 5 seconds later it begins to fade, so you only ever have the last 5 or so seconds of trace at any given time
There is a small error here in the equations of motion. Because the canvas draws the origin in the top left, the derivation used here is slightly wrong. This is accounted for in drawing the pendulum. However the error propagates into the angular acceleration equation. There are two ways to fix this: 1) Fix the equations of motion by doing a coordinate transformation of the solution g -> -g, and cos(angle1) and cos(angle2) also go to negatives. This is actually a bit harder than it looks because there are a lot of trig identities you'd need to pull out to di this. 2) Fix the coordinate system When I implemented this myself using plain old JavaScript the Canvas Context object allows you to scale it by a negative number. Then fix how you draw the pendulums so y = -cos(angle) * length. I believe a way to accomplish this in Processing would be the rotateX() function.
hey, I've encountered the exact same problem you pointed out, could you help me with it in more detail ? I'm kinda lost. For g--> - g, easy to understand but what do I do for the trig identities ? Thanks
And by the way, if you or anyone else want to solve the problem at the end ( I mean that the pendulum is getting higher and higher and even faster) you need to use another way to solve numerically the differential equations. Here you used the Euler method (explicit) ( v += a and x+=v). There is a loose of accuracy because of the integration step. In order to fix it (or to make it better) you can use the RK4-method (Runge Kutta 4) which will make you gain in accuracy without reducing the integration step of time (which is expensive in terms of calculation time). I know it's a bit more complicated but it's worth it ( I personally have tested it with pendulums and with gravity simulation with planets and orbits which can degenerate).
I'm so happy you've done this; I started making one of these in P5 using a class, and I just figured you'd use basic Trig to calculate the angles. Had literally no idea the lre was a huge algorithm derived for it! Gonna give this a looking soon!
Pretty cool! A few things: the dampening should be a function of velocity, proportional using some constant. It would be harder/maybe fun to calculate the forces along the bars and have them extend elastically under the load.
For those who does not understand why at 24:30, switching the velocity before position fixed the problem, here is the technical explanation: it seems like its the same, but if you work out the math, position first is called Euler's method whose error is not bounded. As time goes by, the error will be big enough(if you plot the energy of the system, it continuously goes up) , it seems like it getting more energetic. If you put the velocity before the position, the error is bounded. He accidentally used a method called Verlet method whose error is bounded in this case. therefore, as time goes by, the energy of the system fluctuate within in a range, therefore, it looks real.
You are the one Level 99 developer that I've spent my entire life looking for. If there was a 10th Dan for programmers, it'd be yours. Thanks for existing.
Phone users pause the video at 29:48 and look at the black dot below, go full screen and watch the video vertically you will realise the video bar will curve
The reason that updating the velocities and then the positions works better is because it's a symplectic forward Euler integration scheme which more closely captures the symplectic geometric structure of the (Hamiltonian) double pendulum system, and so you get less numerical integration error. You can also write down the general equations of motion for a generalized pendulum fairly easily in the case where the lengths and masses of the pendulums are the same, and I'm sure it's just a tedious generalization to consider distinct masses and lengths.
You should try to create a simulation with vectors as well, it would be interesting. (Calculate the motions without formulas, just using vectors and addition)
One tiny thing I would change is making the width and height of the masses proportional to the square root of the mass, that way the area is proportional to the mass.
The double pendulum is a system of four first order non-linear differential equations. A better method of approximating the solution would be an ODE solving algorithm like Runge-Kutta. Simply adding acceleration to velocity and velocity to position will only be valid for a very short time interval after release due compounding error.
First of all, c is simply the speed of light, it is NOT 1. In special relativity we treat it as 1 because that's the the ratio speed of light/speed of light = 1 , and other speeds are written in terms of c so it's easier to do lorentz transformations. Physicists don't set constants. Ever. You can't just set a constant to whatever you want.
Pati, clearly you aren't a physicist. There is nothing fundamental about the meter or the second that makes them absolute in any way. All dimensional constants are dependent entirely on the measuring system you use them with. Who sets the measuring system? Physicists. You CAN set the speed of light to whatever you want, just by using whatever length you want. It's not just a notational trick, the speed of light IS one lightyear per year, or one lightsecond per second, etc. The only FUNDAMENTAL constants are the dimensionless ones, like the fine structure constant or the strong coupling constant, dimensional constants like the speed of light and gravitational constants are all secondary.
Pati I think you must understand that anything can be referenced in relation to everything, regarding certain vectors of location and assuming small scale locality and infinite spatial dimensions of said locality. Therefore, symbology and meaning in this world is manifested solely based on our reality and thought processes from the point of which we stand. There’s a reason why everyone else besides the US uses the metric system. Because it’s easier to work with. Why would you want to make things harder for yourself?
The way to calculate the double pendulum is actually not incredibly complex. There's really 2 main things you have to know. 1.) you have to know the physics in order to get a formula for the kinetic and potential energy for each of the masses. 2.) you have to know the Euler-Lagrange equation. you use the formulas for the kinetic and potential energy to get two differential equations, and really the complicated part is the algebra for actually solving for the angular acceleration for theta1 and theta2 because the equations is a little long and both accelerations show up in both equations. The original differential equation is (relatively) simpler and not too complex to see where each part of the equation comes from.
In many controlled systems, theta2 is aligned with the r1. So in your definition theta2 is aligned with the x,y-axis, but a motor controlling theta2 would not know this angle. This would have slightly more difficult trigonometry ;-)
Mathematical art's great for introducing kids to math, physics and programming. This 2D representation of a 3D object captures interesting properties of a double pendulum, but I'd imagine that 2DoF robotic arms (Scara configurations?) probably treat it better. What I'd like to see is a colored map that shows where the pendulum weights spend most of their time and I'd like to see implementations of quantum algorithms to generate it. I'd guess it would resemble a blobby v shape. I bet this has a name and a figure, but I have yet to come across it. Also, if the video outlined coding concepts it covers, it would be more useful for structured learning, for example in school.
P.S. While looking for previous Processing tutorials about double pendulums, this guy popped up and I think he looks like Metro/Music Man; no offense, just an observation. scripps.ucsd.edu/profiles/hstaudigel
Absolutely love you videos. I also found out that if you try to compute the total energy of the system, it is NOT conserved, I wonder what is wrong, everything seems to work fine except that
that is VERY hard to create a double pendulum, just because it's so random and hard! I didn't watched the video yet, because as always; I'm first trying the challenge myself and then trying your code. This one was IMPOSSIBLE!! good job Dan!!!
Not bad, but there has to be a more general formula for it. Because what do you do if you want a triple or quadruple pendulum now? You can't always come up with a new formula, physics is based on general formulas and there is not a separate formula for every possible event.
Hey! I'd love to see you implement the '4th order runge kutta' method for that. What you did (v+=a; x+=v) is called 'Forward Euler Integration', 'Runge Kutta Integration' is basically the same, but with multiple intermediate steps. That achieves an accuracy that goes down two more taylor iterations, removing the 'energy gain' over time.
Now me as a physics student want to make 3D version where all of the formulas are calculated by me! Funny thing is that last semester I had classes called Classical Mechanics and one of the tasks on final exam was to calculate this formulas in double pendulum ;>
use{{ a1_v+=a1_a*t; a2_v+=a2_a*t; a1+=a1_v*t; a2+=a2_v*t;}} this way you can change the defined 't' to any number.because in this code the maths part becomes more and more inaccurate or as the time goes.(i.e as more x,y pairs get drawn on canvas).because the whole mathamatical process in your code is approximated integration but you assume the delta t is 1. By changing the delta t(in my code it's t as you can see ) the integration becomes more accurate.also put 10 for g.
For those interested, formula comes from approximating Runge Kutta numerical solution. You might as well program it so you do not have the need to write the "analytical" solution.
You're using the 1st order Euler method to solve the differential equations, it is very rough and you get the increasing total energy to your system with time. Check please the sum of kinetic and potential energy of the pendulum. To fix the problem you should damp the velocity in such a way that the energy is kept constant.
Rather than calculate the angles, I calculated the force in the connecting rods and used a pair of standard movers, with the child pendulum applying its rod force to the parent pendulum. Seems to work fairly well. I also call canvas.background() with a very transparent color so the trace fades over time.
for proper modeling of dampening consider a force(torque) that applys in counter direction of your movement. F = -d*v the minus accounts for the counter direction: F:= Force (Torqe) depending of your motion Type d:= dampening constant [force/(angular)velocity] V:= (angular)Velocity now say your (angular)acceleration is : a= (insert complicated differential equasion without dampening) - F/m
29:03 actually you don't need that dampening since you have in the g value, since it's 1 it won't really change the result of the formula but if you tweak it to be 9,807 m/s² (earth gravity) it'd change, I like moon, mars and sun values to play with.
The verletphysics framework is very good for simulation ! But, I have a question. I want to simulate a pendulum or a chain. If I want the objects to keep moving without stopping, how should I write the code?
Shouldn't there be slack introduced into the lines whenever a mass does a loop, but doesn't have enough momentum to keep the line tight throughout the entire loop? Visually adding curves to the line when appropriate would make this look much more realistic.
It could be a good beginner project, specifically for people learning to deal with neural networks, to train a neural network to predict a double pendulum.
You were close: g is the local (unsigned) acceleration due to gravity (~9.8 m/s^2 on Earth), G is the universal gravitational constant (some absurd number in absurd units, not gonna write it out). Physicists intentionally name things to be confusing lol
Those 'primes' signs are derivatives Siglne ' means first derivative Double ' ' means second derivative, so basicly derivative of first derivative When function is quite complicated you could use wolfram to calculate derivatives
BTW, those 'crazy' expressions of accelerations can be derived using euler-langrange equation (a part of langrangian mechanics). Infact, It's very simple, not crazy at all :)
i've literally never watched a coding video before (but i've at least taken calc and physics haha) but somehow this made sense, so props to you as a teacher!
Glad to hear! You can use either of these playlists to start from the beginning! ua-cam.com/users/shiffmanplaylists?view=50&shelf_id=14&sort=dd ua-cam.com/users/shiffmanplaylists?view=50&shelf_id=2&sort=dd
g was way too high in the original, that's why it didn't seem as "chaotic" was in real life. Assuming your framerate was 60, and calling the 200 pixels you made the arm a realistic pendulum length, like 1 meter (a clock pendulum that ticks once per second is 99.568cm long), you could get a realistic value for g by taking the approximation of 10 m/s^2 and using the conversions of 1 frame = 1/60 second and 1 meter = 200 pixels, you can turn 10m/s^2 into 2000 pixels/s^2, and then into 0.556pixels/frame^2. , which would be a more appropriate g value. Figuring out a more appropriate mass value is a bit more complicated of a task because using the pixels/frame^2 unit for acceleration screws up the balance of the whole equation if using kg for mass, so you would have to derive a new mass unit, which I think is a bit more work than is fitting for a youtube comment. I may try to make this program later with the new g value and work on how I would figure mass.
One of the reasons you had so much difficulty finding the bugs was because you're repeating yourself in multiple places , you have no separation of concerns (even if just splitting out into different functions) and the naming of your variables is quite hard to translate - instead of what could be a set of a well-named variables that'd assist in debug.
As a Physicist who already did this, i have to tell you. If you think this is fun, you should try finding the equations and then simulating it. Then, do it for N pendulums, and simulate it. THAT'S what i call fun 😎.
I go to know so many things related to coding bcuz of you thanks a lot for making such amazing tutorials. Now I can kinda convert Java into Javascript(as thats the only language I know). They are so fun to follow along!!!
7:36 You could delete that second fill function call just before the ellipse function call you are in this moment, sine the you are just resetting it to the same value. Indeed, the program also works if you move the fill function call to setup()
Pausing it at the beginning to call how he's going to do it, build a single pendulum simulation and then create a piece of code to find the angle of the first pendulum and basically add the second onto the first.
Efficiency upgrade for drawing "lines": You can avoid The IF inside the loop on every interaction by setting the initial previousXY for drawing the lines EQUAL to CurrentXY position. But then: It implies calculating the initial position before the loop. End of Comment
Dan, i would like to challenge you to recreate this but in 3D. Still a double pendulum but can rotate along a z axis aswell. Think this would make a cool project, since it seems like a very difficult thing to recreate in the real world.
I've never worked with Processing so I was kinda confused that you didn't consider the delta time with the changes in x1, v1, a1, etc. Is there something they did in Processing to make that insignificant or would you implement it in a larger projects?
awesome :D i always get so excited when i see a new video on this channel. I even managed to attend some live streams. I love how weird you are :D and how you can explain these pretty complicated concepts in a way that is so easy to understand. I've tried the same with the matter.js library but failed miserably :p nicely done!
Fun fact in case nobody else has mentioned it: updating the positions using the "current velocity" vs the previous one changes the numerical method from Euler's method to the Euler-Cromer method, which is quite a lot more accurate. The regular Euler method is prone to inadvertently increasing the energy of the system, while the Euler-Cromer method conserves energy quite decently. The two methods seem almost identical, but the behind the scenes math is quite interesting and shows that they are actually of different orders.
13:15
Note: the following proof is trivial and has been left as an exercise to the reader
lmfao love those videos
Physics books be like
Lagrange bra.
ua-cam.com/video/tc2ah-KnDXw/v-deo.html
in case you are interested ;)
@ bill bassichis
To those who want to make this simulation more real do this.
Currently Dan is setting g = 1. Although its far from the actual value the simulation looks very real.
This is because one second in the simulation is one frame. And by default processing or p5.js is set to 60 fps.
This means when one second passes in real world, 60 seconds would have passed in the simulation world.
Hence the correct value of g would be 9.8/ ( 60 * 60 ) .
There's still one more thing to adjust. The masses are actually in kilograms hence you should set the value of bob masses to around 0.05 which is 50 grams. Also, the lengths are in meters so make that they aren't very large.
Thanks for these comments!
This Guy has made a magic. But when we give the real numbers within no time, the software is getting into errors. he has very intelligently demonstrated the capabilities given the limitation of a 30 min video. The world appreciated him for this.
Nope
I changed and now it's really really slow
OMG, I've watched a 30 min video without even noticing it. Thanks for existing, Dan!
João Vitor Bonadiman
Same...
When I noticed the video would end soon from the way he talked I looked up the runtime because I hoped there was more to come with messing with the values. Then I noticed I've watched 30 min of coding feeling like 5...
"Okay, I'm gonna see if I can just copy and paste this enormous differential equation right into my code."
“G is the universal gravitational constant, I assume. That’s just gonna be one.”
If only it became true at the moment he wrote it ! Some physics genius would have re-died. ^^
Missing Semicolon I died. Small g is acceleration of gravity on earth = 9.81 m/s^2. Big G is the universal gravitational constant, 6.67 x 10^-11. TRIGGERED!!!
Most of the time you don't use actual real values in code because in order to have them work properly ud have to do a lot more work.
ħ = c = G = 1
This was golden hahahah thank you so much for this
i have no idea wats going on. yet im enjoying this video.
Story of my life online
Same
Same
Like 2 livers connected and if we swing it from the free end, it creates a beautiful art. I guess that's what he did. Not sure.
😂😂😂 Me too
24:10 you are changing the integration method from simple explicit Euler to symplectic Euler which is numerically much more stable.
Top comment!! This explains your astute observation at 23:33 "It's got quite a bounce to it." The simple/forward Euler method tends to artificially add energy to this system, while the symplectic/semi-implicit Euler method is better at conserving energy. There are many other variant methods, including the so-called midpoint method (angle is updated by the average of present and future velocity steps).
W h a t
I found some math gods here...
I really REALLY laughed when the pendulum just started warping into another dimension at 12:30
*"See, this is kind of the idea"*
you just made my day hahahaha
Hahahaha
He just made the flower of life
Was my thought too :D
I think a cool feature to add would be a fade of the trace line, so as a segment of line is drawn, say 5 seconds later it begins to fade, so you only ever have the last 5 or so seconds of trace at any given time
Something like this in draw:
fill(255,10);
rect(0,0,width,height);
You’re one of those special people in the world that make it a better place. You can always tell, and it just radiates from you.
We need more teachers like you, I'm starting to enjoy coding thanks to you!
There is a small error here in the equations of motion. Because the canvas draws the origin in the top left, the derivation used here is slightly wrong. This is accounted for in drawing the pendulum. However the error propagates into the angular acceleration equation.
There are two ways to fix this:
1) Fix the equations of motion by doing a coordinate transformation of the solution
g -> -g, and cos(angle1) and cos(angle2) also go to negatives. This is actually a bit harder than it looks because there are a lot of trig identities you'd need to pull out to di this.
2) Fix the coordinate system
When I implemented this myself using plain old JavaScript the Canvas Context object allows you to scale it by a negative number. Then fix how you draw the pendulums so y = -cos(angle) * length. I believe a way to accomplish this in Processing would be the rotateX() function.
Thank you for this feedback!
hey, I've encountered the exact same problem you pointed out, could you help me with it in more detail ? I'm kinda lost. For g--> - g, easy to understand but what do I do for the trig identities ? Thanks
I never knew i could be so engaged and laugh at someone doing something like this. Great video! :)
This is the best UA-cam channel I've ever seen
And by the way, if you or anyone else want to solve the problem at the end ( I mean that the pendulum is getting higher and higher and even faster) you need to use another way to solve numerically the differential equations.
Here you used the Euler method (explicit) ( v += a and x+=v).
There is a loose of accuracy because of the integration step.
In order to fix it (or to make it better) you can use the RK4-method (Runge Kutta 4) which will make you gain in accuracy without reducing the integration step of time (which is expensive in terms of calculation time).
I know it's a bit more complicated but it's worth it ( I personally have tested it with pendulums and with gravity simulation with planets and orbits which can degenerate).
Idk why this was recommenced to me, I never even coded, but you're so full of energy and entertaining, thumbs up dude
I'm so happy you've done this; I started making one of these in P5 using a class, and I just figured you'd use basic Trig to calculate the angles. Had literally no idea the lre was a huge algorithm derived for it! Gonna give this a looking soon!
It's so satisfying to see the joy on his face as if he became a father😄great man to be convinced to get into coding
The first time i see, why i had to learn all the Math in school xD
All those physics courses really made me understand this, I'd be lost without taking those courses tbh.
Pretty cool! A few things: the dampening should be a function of velocity, proportional using some constant. It would be harder/maybe fun to calculate the forces along the bars and have them extend elastically under the load.
thanks for this feedback!
THIS IS A PERFECT EXAMPLE OF HOW TO DO AND HANDLE COMPLEX PROJECTS AND COMPLEX ALGORITHM. YOU'RE GREAT!!
"I'm not going to derive those formulas" *cries in physics major
@@xxxh4x0rxxx21 more easy to use Hamiltonian
@@termitori Hamiltonian is advanced Lagrange
@@mr.mirror1213 but it makes it so easy. the hamiltonian destroys everything you thought you knew about classical mechanics and it's fucking beautiful
Exactly man, after using lagrangian it bacame easior
First video I watch from this genius. You’re funny as hell, your channel’s gonna get me hooked. Thanks.
17:49
"Oh I forgot a semi colon"
Me: (Laughs in Python)
Imagine running your programs at 60 fps
Me: laughs in c++
@@killereks imagine not having Dynamic Memory Allocation
Me: also laughs in python
@@thewild2334 imagine spending too much memory on a slow list.
Me: laughs in C
@@killereks Imagine running your program in the browser.
Me: laughs in JavaScript
why did you guys stop??
For those who does not understand why at 24:30, switching the velocity before position fixed the problem, here is the technical explanation:
it seems like its the same, but if you work out the math, position first is called Euler's method whose error is not bounded. As time goes by, the error will be big enough(if you plot the energy of the system, it continuously goes up) , it seems like it getting more energetic. If you put the velocity before the position, the error is bounded. He accidentally used a method called Verlet method whose error is bounded in this case. therefore, as time goes by, the energy of the system fluctuate within in a range, therefore, it looks real.
You are surely the best coding tutor available
You are the one Level 99 developer that I've spent my entire life looking for. If there was a 10th Dan for programmers, it'd be yours. Thanks for existing.
"I'm right about the angular acceleration, because it's going in a perfect circle"
- Dan 2018
this is the first of your videos i have seen, i am so glad people actally go through these sort of things for others to see
keep up the good work :)
Phone users pause the video at 29:48 and look at the black dot below, go full screen and watch the video vertically you will realise the video bar will curve
Dude you are a gifted individual.
22:50 The most beautiful sound you can hear...
The reason that updating the velocities and then the positions works better is because it's a symplectic forward Euler integration scheme which more closely captures the symplectic geometric structure of the (Hamiltonian) double pendulum system, and so you get less numerical integration error. You can also write down the general equations of motion for a generalized pendulum fairly easily in the case where the lengths and masses of the pendulums are the same, and I'm sure it's just a tedious generalization to consider distinct masses and lengths.
Thanks for this information!
You should try to create a simulation with vectors as well, it would be interesting.
(Calculate the motions without formulas, just using vectors and addition)
One tiny thing I would change is making the width and height of the masses proportional to the square root of the mass, that way the area is proportional to the mass.
The double pendulum is a system of four first order non-linear differential equations. A better method of approximating the solution would be an ODE solving algorithm like Runge-Kutta. Simply adding acceleration to velocity and velocity to position will only be valid for a very short time interval after release due compounding error.
Make a pendulum wave, multiple pendulums with differents arm length, that effect is pretty awesome !!
15:00 you hurt the physicist in me so darn hard XD
René Carannante Actually, that's exactly what a physicist would have done. We set constants to 1 all the time. Like in relativity, c is always 1
First of all, c is simply the speed of light, it is NOT 1. In special relativity we treat it as 1 because that's the the ratio speed of light/speed of light = 1 , and other speeds are written in terms of c so it's easier to do lorentz transformations.
Physicists don't set constants. Ever. You can't just set a constant to whatever you want.
Pati, clearly you aren't a physicist. There is nothing fundamental about the meter or the second that makes them absolute in any way. All dimensional constants are dependent entirely on the measuring system you use them with. Who sets the measuring system? Physicists. You CAN set the speed of light to whatever you want, just by using whatever length you want. It's not just a notational trick, the speed of light IS one lightyear per year, or one lightsecond per second, etc.
The only FUNDAMENTAL constants are the dimensionless ones, like the fine structure constant or the strong coupling constant, dimensional constants like the speed of light and gravitational constants are all secondary.
Pati I think you must understand that anything can be referenced in relation to everything, regarding certain vectors of location and assuming small scale locality and infinite spatial dimensions of said locality. Therefore, symbology and meaning in this world is manifested solely based on our reality and thought processes from the point of which we stand.
There’s a reason why everyone else besides the US uses the metric system. Because it’s easier to work with. Why would you want to make things harder for yourself?
@@pati7132 I agree
I just found my new favorite channel.
Amazing... Chaos moviment.. and the butterfly effect. You are great!
The way to calculate the double pendulum is actually not incredibly complex. There's really 2 main things you have to know. 1.) you have to know the physics in order to get a formula for the kinetic and potential energy for each of the masses. 2.) you have to know the Euler-Lagrange equation. you use the formulas for the kinetic and potential energy to get two differential equations, and really the complicated part is the algebra for actually solving for the angular acceleration for theta1 and theta2 because the equations is a little long and both accelerations show up in both equations. The original differential equation is (relatively) simpler and not too complex to see where each part of the equation comes from.
In many controlled systems, theta2 is aligned with the r1. So in your definition theta2 is aligned with the x,y-axis, but a motor controlling theta2 would not know this angle. This would have slightly more difficult trigonometry ;-)
g is acceleration due to gravity
G is the universal gravitational constant
Mathematical art's great for introducing kids to math, physics and programming. This 2D representation of a 3D object captures interesting properties of a double pendulum, but I'd imagine that 2DoF robotic arms (Scara configurations?) probably treat it better. What I'd like to see is a colored map that shows where the pendulum weights spend most of their time and I'd like to see implementations of quantum algorithms to generate it. I'd guess it would resemble a blobby v shape. I bet this has a name and a figure, but I have yet to come across it.
Also, if the video outlined coding concepts it covers, it would be more useful for structured learning, for example in school.
P.S. While looking for previous Processing tutorials about double pendulums, this guy popped up and I think he looks like Metro/Music Man; no offense, just an observation.
scripps.ucsd.edu/profiles/hstaudigel
Go Dan! GO!
Absolutely love you videos. I also found out that if you try to compute the total energy of the system, it is NOT conserved, I wonder what is wrong, everything seems to work fine except that
that is VERY hard to create a double pendulum, just because it's so random and hard! I didn't watched the video yet, because as always; I'm first trying the challenge myself and then trying your code. This one was IMPOSSIBLE!! good job Dan!!!
This was my second year BSc Physics coding project (circa 2016). It was hardcore, but definitly do-able :D
That probably the craziest formula I've ever seen
Not bad, but there has to be a more general formula for it. Because what do you do if you want a triple or quadruple pendulum now? You can't always come up with a new formula, physics is based on general formulas and there is not a separate formula for every possible event.
Hey! I'd love to see you implement the '4th order runge kutta' method for that. What you did (v+=a; x+=v) is called 'Forward Euler Integration', 'Runge Kutta Integration' is basically the same, but with multiple intermediate steps. That achieves an accuracy that goes down two more taylor iterations, removing the 'energy gain' over time.
Yes, it would be nice to cover this sometime!
I did that here for multiple pendula: github.com/kevinhp/multiplePendula
See here for a working implementation:
www.openprocessing.org/sketch/507468
Cheers, Daniel
Now me as a physics student want to make 3D version where all of the formulas are calculated by me! Funny thing is that last semester I had classes called Classical Mechanics and one of the tasks on final exam was to calculate this formulas in double pendulum ;>
Sounds hella fun. Would love to see a 3d version!
Morszczux Lagrangians save lives
Mr. Fluffypantz True!
Next challenge
Gravitational Waves
Purifier Phoenix The Mecca hell yeah
12:43 hmm that pendulum looks like a famous logo... that's a new brand I believe?
man , watching this smart and fun guy is another level of happiness :D !
This code helped me make a spirograph generator.
You are simply awesome!!!
use{{ a1_v+=a1_a*t;
a2_v+=a2_a*t;
a1+=a1_v*t;
a2+=a2_v*t;}}
this way you can change the defined 't' to any number.because in this code the maths part becomes more and more inaccurate or as the time goes.(i.e as more x,y pairs get drawn on canvas).because the whole mathamatical process in your code is approximated integration but you assume the delta t is 1. By changing the delta t(in my code it's t as you can see ) the integration becomes more accurate.also put 10 for g.
For those interested, formula comes from approximating Runge Kutta numerical solution. You might as well program it so you do not have the need to write the "analytical" solution.
Wow, Dan! I didn't know you are so good at object oriented programming!
You're using the 1st order Euler method to solve the differential equations, it is very rough and you get the increasing total energy to your system with time. Check please the sum of kinetic and potential energy of the pendulum. To fix the problem you should damp the velocity in such a way that the energy is kept constant.
Rather than calculate the angles, I calculated the force in the connecting rods and used a pair of standard movers, with the child pendulum applying its rod force to the parent pendulum. Seems to work fairly well. I also call canvas.background() with a very transparent color so the trace fades over time.
for proper modeling of dampening consider a force(torque) that applys in counter direction of your movement.
F = -d*v
the minus accounts for the counter direction:
F:= Force (Torqe) depending of your motion Type
d:= dampening constant [force/(angular)velocity]
V:= (angular)Velocity
now say your (angular)acceleration is :
a= (insert complicated differential equasion without dampening) - F/m
29:03 actually you don't need that dampening since you have in the g value, since it's 1 it won't really change the result of the formula but if you tweak it to be 9,807 m/s² (earth gravity) it'd change, I like moon, mars and sun values to play with.
I know absolutely nothing about coding and all of this is foreign to me but I love watching you lol
Quick wallpaper I did using this: i.imgur.com/BSb37so.png
Cédric Reber nice wallpaper
Too Good
5:40 - You could have used the sine rule: Sin(90) /r1 = Sin(Theta1) / x and then rearranged to make x the subject. A little more effective.
Thanks for the tip!
The verletphysics framework is very good for simulation !
But, I have a question. I want to simulate a pendulum or a chain.
If I want the objects to keep moving without stopping, how should I write the code?
Shouldn't there be slack introduced into the lines whenever a mass does a loop, but doesn't have enough momentum to keep the line tight throughout the entire loop? Visually adding curves to the line when appropriate would make this look much more realistic.
It could be a good beginner project, specifically for people learning to deal with neural networks, to train a neural network to predict a double pendulum.
r1 and r2 are supposed to be strings i guess. in the vid, they'r just rods. strings will require more messing around, lots of if/else statements.
You were close: g is the local (unsigned) acceleration due to gravity (~9.8 m/s^2 on Earth), G is the universal gravitational constant (some absurd number in absurd units, not gonna write it out).
Physicists intentionally name things to be confusing lol
you are a blessing !!!! a true blessing. I cant thank you enough for what you are doing.
95/5000
it will not be the same pattern, the inverted pendulum is a non-linear and chaotic system ... great work
Those 'primes' signs are derivatives
Siglne ' means first derivative
Double ' ' means second derivative, so basicly derivative of first derivative
When function is quite complicated you could use wolfram to calculate derivatives
this is the best way to learn how to convert equation to codee!
Thanks for introducing me to Processing....
The pendulum going crazy is my favoirite part
the lagrange equations were fun.
BTW, those 'crazy' expressions of accelerations can be derived using euler-langrange equation (a part of langrangian mechanics). Infact, It's very simple, not crazy at all :)
i've literally never watched a coding video before (but i've at least taken calc and physics haha) but somehow this made sense, so props to you as a teacher!
Glad to hear! You can use either of these playlists to start from the beginning!
ua-cam.com/users/shiffmanplaylists?view=50&shelf_id=14&sort=dd
ua-cam.com/users/shiffmanplaylists?view=50&shelf_id=2&sort=dd
g was way too high in the original, that's why it didn't seem as "chaotic" was in real life. Assuming your framerate was 60, and calling the 200 pixels you made the arm a realistic pendulum length, like 1 meter (a clock pendulum that ticks once per second is 99.568cm long), you could get a realistic value for g by taking the approximation of 10 m/s^2 and using the conversions of 1 frame = 1/60 second and 1 meter = 200 pixels, you can turn 10m/s^2 into 2000 pixels/s^2, and then into 0.556pixels/frame^2. , which would be a more appropriate g value. Figuring out a more appropriate mass value is a bit more complicated of a task because using the pixels/frame^2 unit for acceleration screws up the balance of the whole equation if using kg for mass, so you would have to derive a new mass unit, which I think is a bit more work than is fitting for a youtube comment. I may try to make this program later with the new g value and work on how I would figure mass.
Thanks for this comment!
I thought it was because you messed up - and + in the calculation of a1_1 ?
a1_a
One of the reasons you had so much difficulty finding the bugs was because you're repeating yourself in multiple places , you have no separation of concerns (even if just splitting out into different functions) and the naming of your variables is quite hard to translate - instead of what could be a set of a well-named variables that'd assist in debug.
Great points!
Update the velocity before the position, it is a more stable integration method (semi-implicit euler integration)
haha, double pendulums are great
lol
You do great videos, congrats!!!
Even at *0.999 it shouldn't take long for it to stop moving. It'll be at 1% of it's initial velocity after about 4600 frames, so maybe a minute.
As a Physicist who already did this, i have to tell you.
If you think this is fun, you should try finding the equations and then simulating it.
Then, do it for N pendulums, and simulate it.
THAT'S what i call fun 😎.
I go to know so many things related to coding bcuz of you thanks a lot for making such amazing tutorials. Now I can kinda convert Java into Javascript(as thats the only language I know). They are so fun to follow along!!!
7:36 You could delete that second fill function call just before the ellipse function call you are in this moment, sine the you are just resetting it to the same value. Indeed, the program also works if you move the fill function call to setup()
Pausing it at the beginning to call how he's going to do it, build a single pendulum simulation and then create a piece of code to find the angle of the first pendulum and basically add the second onto the first.
I think it is better to use vectors for this one
Efficiency upgrade
for drawing "lines":
You can avoid
The IF inside the loop
on every interaction by
setting the initial previousXY
for drawing the lines EQUAL
to CurrentXY position.
But then:
It implies calculating
the initial position
before the loop.
End of Comment
Dan, i would like to challenge you to recreate this but in 3D. Still a double pendulum but can rotate along a z axis aswell. Think this would make a cool project, since it seems like a very difficult thing to recreate in the real world.
Two strings Two masses and a conection to the celling. but a simulation would be cool either way.
The second angle for the formula is positive going clockwise but you did It positive counterclockwise
What environment do you code in? How can you have all the methods without having to import a library? Also is that java?
I've never worked with Processing so I was kinda confused that you didn't consider the delta time with the changes in x1, v1, a1, etc. Is there something they did in Processing to make that insignificant or would you implement it in a larger projects?
awesome :D i always get so excited when i see a new video on this channel. I even managed to attend some live streams.
I love how weird you are :D and how you can explain these pretty complicated concepts in a way that is so easy to understand.
I've tried the same with the matter.js library but failed miserably :p nicely done!
G IS a gravitational constant that IS equal to 10