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

使用Skyfield/Scipy将木星AU距离转光年遇ValueError求助

问题:木星AU距离转光年时触发ValueError错误

我尝试用Skyfield(skyfield.api)和Scipy模块将木星的天文单位(AU)距离转换为光年,Python版本为3.9.12,但运行代码时遇到了错误。

原代码

from scipy import constants
from skyfield.api import load
planets = load('de421.bsp')
earth, jupiter = planets['earth'], planets['JUPITER BARYCENTER']
ts = load.timescale()
t = ts.now()
astrometric = earth.at(t).observe(jupiter)
radec=astrometric.radec()

# 最初尝试的无效代码
# int(constants.astronomical_unit / constants.light_year ) * int(str(radec[2])

# 后续修改后的代码
int(constants.astronomical_unit / constants.light_year ) * int(str(radec[2]).replace("au", "").strip())

错误信息

ValueError: invalid literal for int() with base 10: '4.63954'

问题原因

你试图将带小数的字符串(如'4.63954')直接转换为整数,但int()只能解析纯整数格式的字符串,这是触发错误的核心原因。此外,通过字符串提取距离值的做法完全没必要——Skyfield提供了直接获取数值化距离的方法,无需手动处理字符串。

修正方案

直接通过Skyfield的distance.au属性获取木星与地球的AU距离(浮点数类型),再乘以AU转光年的系数即可:

from scipy import constants
from skyfield.api import load

planets = load('de421.bsp')
earth, jupiter = planets['earth'], planets['JUPITER BARYCENTER']
ts = load.timescale()
t = ts.now()

# 获取AU单位的距离数值
distance_au = earth.at(t).observe(jupiter).distance.au

# 计算1AU对应的光年数
au_to_lightyear = constants.astronomical_unit / constants.light_year

# 转换为光年
distance_lightyear = distance_au * au_to_lightyear

# 打印结果(保留6位小数)
print(f"木星当前距离地球约 {distance_lightyear:.6f} 光年")

说明

  1. astrometric.distance.au直接返回浮点数形式的AU距离,避免了字符串解析的麻烦和错误
  2. 转换系数au_to_lightyear是固定值(约1.58125e-5光年/AU),用Scipy的常量计算更准确
  3. 最终结果保留小数位更符合天文距离的实际精度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:25:23