Solving differential equations using numeric methods

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 1K views
DarkBabylon
Messages
72
Reaction score
10
Hello, I have been working on a little movement system in a program called Game Maker: studio.
The code works fine on the programming perspective, but something I did not expect happened:
When I ran the code by adding to the speed while pressing a key, and every step passively subtracting from the speed I got a certain number I did not expect to find.
Essentially the code run like this:
if key=pressed {speed+=2};
speed-=0.25*speed;
Which according to the game maker syntax should add to the speed while the key is pressed by 2 pixels per step, and afterwards it will subtract from the speed what would be equal a quarter of the speed previously calculated.
With this method I got top speed of 6 pixels per step.
However when I just put out the entire differential equation under the key press 'if' statement, it returned a top speed of 8 pixels per step, which was exactly as an analytical analysis would predict.

Question is, why is it so? Can't seem to get why would that matter at least not at hindsight.
 
Physics news on Phys.org
perhaps you want the speed -= speed*0.25 to be in an else clause

that way pressing the key increments the speed and not pressing it reduces the speed.

Right now when pressing the key it adds 2 then then effectively subtracts a quarter of the speed.
Code:
loop 1: 10     -> 12    -> 9
loop 2: 9      -> 11    -> 8.25
loop 3: 8.25   -> 10.25 -> 7.68
 
The value of speed = 6 is a steady state when the key is pressed. If speed=6 before the code, then speed + 2 - .25 *( speed+2) = 6 + 2 - .25*(6+2) = 6 + 2 - 2 = 6 after the code. If you put a print statement after the 'if' line, then speed=8 at that point. Is that what you expected?