Discord Python Bot的?pi命令小数位数不足问题求助
问题修复方案
你的代码存在两个核心问题,导致返回的圆周率小数位数比预期少一位:
1. 字符串截取长度计算错误
pi_str = str(pi_value)[:num_decimals + 1] 这行的截取逻辑有误。圆周率的字符串格式为3.xxxxxx,包含1位整数、1个小数点,再加上num_decimals位小数,总长度应为num_decimals + 2。当前截取长度仅取到num_decimals +1,相当于丢失了最后一位小数。
2. 计算精度与迭代次数不足
使用BBP公式计算圆周率时,原有的迭代次数和精度设置无法完全保证最后一位小数的准确性,需要预留一定冗余空间。
修复后的完整代码
import decimal import discord from discord.ext import commands from discord.ext.commands import has_permissions, MissingPermissions #token token = "hidden" #intents and prefix intents = discord.Intents.default() bot = commands.Bot(command_prefix="?", intents=intents) #basic events @bot.event async def on_ready(): print('We have logged in as {0.user}'.format(bot)) @bot.event async def on_message(message): if message.author == bot.user: return await bot.process_commands(message) #fun commands @bot.command() async def pi(ctx, num_decimals: int): if num_decimals > 10000: await ctx.send("Sorry, I can only print up to 10000 decimal places.") return # 设置总有效数字:整数位1位 + 目标小数位 + 2位冗余确保精度 decimal.getcontext().prec = num_decimals + 3 pi_value = decimal.Decimal(0) # 增加迭代次数冗余,保证计算出足够的有效位数 for i in range(num_decimals + 3): pi_value += (decimal.Decimal(1) / 16 ** i) * ((decimal.Decimal(4) / (8 * i + 1)) - (decimal.Decimal(2) / (8 * i + 4)) - (decimal.Decimal(1) / (8 * i + 5)) - (decimal.Decimal(1) / (8 * i + 6))) # 截取正确长度:整数位+小数点+目标小数位 pi_str = str(pi_value)[:num_decimals + 2] await ctx.send(f"The value of pi to {num_decimals} decimal places is: {pi_str}") try: bot.run(token) except discord.HTTPException as e: if e.status == 429: print("The Discord servers denied the connection for making too many requests") else: raise e
关键修改说明
- 调整字符串截取长度为
num_decimals +2,确保包含完整的num_decimals位小数 - 将
decimal.getcontext().prec设置为num_decimals +3,预留冗余精度避免计算截断 - 迭代次数增加到
num_decimals +3,保证BBP公式计算出足够的有效位数,确保最后一位小数准确
测试输入?pi 100即可得到符合预期的100位小数结果。
内容的提问来源于stack exchange,提问作者user19932233
相关产品推荐
相关产品推荐

