You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

狭义相对论飞船计算代码问题:仅首测试用例输出正确求排查

问题排查与修正

核心问题:旅行时间计算公式错误

你的calculate_travel_time函数中,狭义相对论时间膨胀的应用逻辑颠倒了。根据测试用例的预期结果,这里需要计算的是飞船参考系下的固有时,正确公式应为:
固有时 = 地面参考系光行时间 × √(1 - (v/c)²)
而你当前的代码使用了除法(distance / √(1 - (v/c)²)),导致结果偏大,与预期不符。

另外,代码中多次引入光速c的具体数值是冗余的——因为v/c直接等于输入的速度百分比除以100,完全可以简化计算,避免不必要的浮点运算误差。

修正后的代码

def einstein_factor(velocity):
    # 直接用速度占比计算洛伦兹因子,无需引入光速c
    beta = velocity / 100.0
    factor = 1 / (1 - beta**2) ** 0.5
    return factor

def calculate_travel_time(distance, velocity):
    # 计算飞船参考系的旅行固有时
    beta = velocity / 100.0
    time = distance * (1 - beta**2) ** 0.5
    return time

def main():
    velocity = float(input("Velocity as a % of the speed of light: "))
    mass = float(input("Mass of the spaceship at rest (kg): "))

    traveling_mass = mass * einstein_factor(velocity)
    print("Mass of Spaceship: {:.3f} kg".format(traveling_mass))

    alpha_centauri_time = calculate_travel_time(4.3, velocity)
    barnards_star_time = calculate_travel_time(6.0, velocity)
    betelgeuse_time = calculate_travel_time(309, velocity)
    andromeda_galaxy_time = calculate_travel_time(2000000, velocity)

    print("Time to travel to Alpha Centauri: {:.3f} light years".format(alpha_centauri_time))
    print("Time to travel to Barnard's Star: {:.3f} light years".format(barnards_star_time))
    print("Time to travel to Betelgeuse: {:.3f} light years".format(betelgeuse_time))
    print("Time to travel to Andromeda Galaxy: {:.3f} light years".format(andromeda_galaxy_time))

if __name__ == "__main__":
    main()

验证结果

修正后运行三个测试用例,结果将完全匹配预期:

  • 示例2中,50%光速下Alpha Centauri的旅行时间为4.3 × √(1 - 0.5²) ≈ 3.724
  • 示例3中,99.99%光速下Alpha Centauri的旅行时间为4.3 × √(1 - 0.9999²) ≈ 0.061

内容的提问来源于stack exchange,提问作者Brian Quintero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 02:36:00