Python 为什么会有这段代码?
我试图理解这段代码,实际上我理解了整个过程,除了这两行:Python 为什么会有这段代码?,python,physics,vpython,glowscript,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 我也没有得
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):
(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()
返回单位向量,因此结果是向量而不是标量。这是牛顿引力的矢量形式。(见附件)
.mag2
的作用与**2
的作用相同,但一般来说,向量的幂没有定义,因此在向量类上定义求幂运算符没有意义 更具体地说,mag2给出了向量的2-范数。2-范数基本上是欧几里德距离,或“乌鸦飞”。1-norm是“出租车距离”——一次只能在一个维度上移动的距离。所以的2-范数是sqrt(2),1-范数是2。
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