Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Solving differential equations using numeric methods

  1. Oct 26, 2016 #1
    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};
    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.
  2. jcsd
  3. Oct 26, 2016 #2


    Staff: Mentor

    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 (Text):

    loop 1: 10     -> 12    -> 9
    loop 2: 9      -> 11    -> 8.25
    loop 3: 8.25   -> 10.25 -> 7.68
  4. Oct 27, 2016 #3


    User Avatar
    Science Advisor
    Gold Member
    2017 Award

    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?
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted