为什么会有这段代码?

Why has this piece of code to be there?

我试着理解这段代码,实际上我理解了除了这两行之外的所有内容:

f_grav = gravity * sun.mass * earth.mass * (sun.pos - earth.pos).norm() / (sun.pos - earth.pos).mag2
earth.vel = earth.vel + (f_grav/earth.mass) * dt

为什么不能只是:f_grav = gravity * sun.mass * earth.mass / (sun.pos-earth.pos)**2

我也没有得到 .norm().mag2

的角色

这是程序的完整代码片段 (GlowScript):

sunRadius = 10 * realSunRadius   # the size for our solar system
earthRadius = sunRadius * 0.25    # note: real value would be sunRadius * 0.01, a good choice for sim is * 0.25
astronomicalUnit = 212.7 * realSunRadius     # the distance from Sun to Earth - the Sun is about 100 Sun diameters away      
gravity = 6.6e-11   # sets the strength of the gravitational constant to 6.6x10-11 Newton x meters squared per kilograms squared

# create the Sun object
sun = sphere( radius = sunRadius, opacity = 0.7, emissive = True, texture = "http://i.imgur.com/yoEzbtg.jpg" ) 
sun.mass = 2e30   # mass of the Sun in kilograms is 2,000,000,000,000,000,000,000,000,000,000 kg
sun.pos = vec(0,0,0)
sun.vel = vec(0,0,0)

# place a few sources of light at the same position as the Sun to illuminate the Earth and Moon objects
sunlight = local_light( pos = vec(0,0,0), color=color.white )
more_sunlight = local_light( pos = vec(0,0,0), color=color.white )  # I found adding two lights was about right

# create the Earth object
earth = sphere ( radius = earthRadius, texture = "http://i.imgur.com/rhFu01b.jpg",make_trail=True)
earth.mass = 6e24   # mass of Earth in kilograms
earth.pos = vec(astronomicalUnit, 0, 0)
earth.vel = vec(0,0,-30000)   # the Earth is moving around 30000 m/s


dt = 10000


# below is the main loop of the program - everything above is "setup" and now we are in the main "loop" where all the action occurs
while (True):   # this will make it loop forever

    rate(100)   # this limits the animation rate so that it won't depend on computer/browser processor speed

    # calculate the force of gravity on each object
    f_grav = gravity * sun.mass * earth.mass * (sun.pos - earth.pos).norm() / (sun.pos - earth.pos).mag2
    earth.vel = earth.vel + (f_grav/earth.mass) * dt


    # update the position of the Earth and Moon by using simple circle trigonometry
    earth.pos = earth.pos + earth.vel * dt 

(sun.pos-earth.pos) 是一个向量。我不认为你可以做 (sun.pos-earth.pos)**2 因为你不能平方矢量。除非你想用自己做向量的点积?但是点积的结果是一个标量,所以 f_grav 将是一个标量。力是矢量,所以在那里使用点积没有意义。

相比之下,f_grav = gravity * sun.mass * earth.mass * (sun.pos - earth.pos).norm() / (sun.pos - earth.pos).mag2 有意义,因为您将 (sun.pos - earth.pos).norm() 一个向量乘以三个标量,再除以一个标量。所以结果是一个所需的向量。

.norm() returns 单位向量,因此结果是向量而不是标量。这就是牛顿引力的矢量形式。 (参见 Wikipedia

.mag2 的作用与 **2 的预期相同,但一般而言,向量的幂未定义,因此在矢量class。