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

求助:Python中用while函数计算圆周率及多边形法计算异常问题

Fixing Your Pi Calculation with Python's while Loop

Hey there! It's awesome you're experimenting with calculating Pi using a geometric approach—let's figure out why your results are off and get you on track.

Common Issues Causing Deviation

Let's break down the most likely reasons your Python code isn't matching your calculator results:

  1. Forgetting to convert degrees to radians
    Python's math.cos() function expects angles in radians, not degrees. If you're passing the angle x directly (in degrees), the cosine value will be way off, which throws off the entire calculation. This is almost certainly your main problem.

  2. Floating-point precision limits (secondary issue)
    As x gets extremely small, floating-point numbers in Python (which use double-precision) start to lose precision, but this is usually a problem only after many iterations. Fixing the radian conversion should get you most of the way there.

Corrected Code Example

Here's a revised version of your approach, with step-by-step explanations:

import math

def calculate_pi():
    r = 1.0  # Use radius 1 to simplify calculations
    x_deg = 180.0  # Start with a large angle (we'll keep shrinking it)
    tolerance = 1e-10  # Stop when angle is smaller than this threshold
    
    while x_deg > tolerance:
        # Critical step: convert angle from degrees to radians for math.cos()
        x_rad = math.radians(x_deg)
        # Calculate side length using the Law of Cosines
        side_length = math.sqrt(2 * r**2 - 2 * r**2 * math.cos(x_rad))
        # Number of sides in the polygon
        num_sides = 360.0 / x_deg
        # Polygon perimeter (approximates circle circumference)
        perimeter = num_sides * side_length
        # Pi = circumference / (2*r) (since circle circumference = 2πr)
        pi_approx = perimeter / (2 * r)
        
        # Print progress to see convergence
        print(f"Angle: {x_deg:.8f} degrees | Pi approximation: {pi_approx:.10f}")
        
        # Halve the angle for the next iteration (more sides = closer to a circle)
        x_deg /= 2

calculate_pi()

How This Works

  • Radian Conversion: math.radians(x_deg) translates your degree-based angle into the units math.cos() requires. This fixes the core error in your original code.
  • Iterative Refinement: By halving the angle each loop, we're creating a polygon with more sides, which gets progressively closer to a perfect circle.
  • Simplified Radius: Using r=1 removes unnecessary multiplication/division, making the math easier to follow.

What to Expect

When you run this, you'll see the approximation get closer to the true value of Pi (~3.1415926535...) as the angle shrinks:

  • With x_deg=180, you'll get a rough result (it's a 2-sided "polygon," so Pi≈1—makes sense for a straight line)
  • By x_deg=0.0001, the approximation will be nearly indistinguishable from the actual Pi value.

Bonus Tip

If you want to stop when the approximation stops changing (instead of using an angle tolerance), you can track the previous Pi value and break the loop when the difference is smaller than a threshold like 1e-12. That's a more robust way to know when you've converged.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:26:40