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

Python while循环重复时n_tri无法恢复初始值的技术问题

问题解决方法

你的核心问题是每次重复计算时没有重置三角形数量和误差值。当前代码里n_tri和error只在程序启动时初始化一次,第一次计算后它们的值已经是满足上一次精度的结果了,下次就算精度降低,也不会从头开始计算。

修正方案很简单:把n_tri = 8和error = 1移到外层的while flag_acc:循环里面,每次开始新的精度请求时,都重置这两个变量到初始状态。

修正后的代码:

import math
flag_acc = True
r = 1

while flag_acc:
    # 每次循环都重置初始三角形数量和误差值
    n_tri = 8
    error = 1
    
    accuracy_desired = float(input('To what accuracy would you like pi? (enter number of decimal places desired)'))
    acc_des = 1/(10**accuracy_desired)
    
    while error > acc_des:
        theta_deg = 360/n_tri
        theta_rad = math.radians(theta_deg)
        c = math.sqrt(2 - 2*math.cos(theta_rad))
        circum = c*n_tri
        pie = circum/2
        n_tri += 1
        error = ((math.pi - pie)/math.pi)
    
    print('Accuracy desired was: %0.3e'%(acc_des))
    print('The number of triangles used to meet the desired accuracy was: ', n_tri)
    print('Estimate for pi based on number of triangles is: ', pie)
    
    repeat = input('Would you like to repeat with a new precision? (y/n)')
    if repeat in ['n', 'N']:
        flag_acc = False

为什么之前的尝试没生效?

你之前把n_tri放在循环外部,那它只会初始化一次;如果放在内层循环里,那每次内层循环都会重置,根本没法累积计算到满足精度的数量。只有放在外层循环的开头,每次用户要新的精度时,才会从初始的8个三角形开始重新计算,不管这次精度比上次高还是低。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:40:38