Python Euler Method implementation in Two Body Problem not working

后端 未结 2 1186
死守一世寂寞
死守一世寂寞 2020-12-18 11:03

I am currently trying to get a two body problem to work, that I can then upgrade to more planets, but it is not working. It is outputting me impossible positions. Does anyon

2条回答
  •  无人及你
    2020-12-18 11:34

    I think the core of your problem is that you are not thinking of it as a state engine.

    Imagine "Bodies" is a completely unchangable value that determines the state of the system at one point in time:

    bodies_at_time_0 = ((sun, position, velocity, mass), (earth, position, velocity, mass))
    

    You get the next state like so:

    bodies_at_time_1 = apply_euler_method_for_one_tick( bodies_at_time_0 )
    

    Thus your "Bodies" is completely fixed at one time, and you compute a whole new "Bodies" for the next time. Inside the computation you ALWAYS use the data in the input, which is where they are now. What you are doing is moving some things, and then computing where to move other things based on the wrong number (because you already moved other stuff).

    Once you make sure your function uses the input state, and returns an output state, you can break it down much more easily:

    # advance all bodies one time interval, using their frozen state 
    def compute(bodies):
        new_bodies = []
        for body in bodies:
            new_bodies.append(compute_one_body(body, bodies))
        return new_bodies
    
    # figure out where one body will move to, return its new state
    def compute_one_body(start, bodies):
        end = math stuff using the fixed state in bodies
        return end
    
    # MAIN
    bodies = initial_state
    for timepoint in whatever:
        bodies = compute(bodies)
    

    I like to use tuples for this sort of thing, to avoid accidentally changing a list in some other scope (because lists are mutable).

提交回复
热议问题