为什么会有这段代码?

时间:2018-06-26 14:01:33

标签: python physics vpython glowscript

我试图理解这段代码,但实际上我理解了除了这两行之外的全部内容:

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 

2 个答案:

答案 0 :(得分:1)

(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()乘以三个标量,然后除以一个标量。因此结果就是所需的向量。

答案 1 :(得分:1)

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

.mag2**2的预期功能相同,但是通常不定义向量的幂,因此在向量类上定义幂运算符没有任何意义。