Python新手求助:如何完成求x平方根的实验算法?
Hey there! As a Python newbie working on this square root algorithm, you’ve already taken a great first step by starting with an initial guess. Let’s expand on that using the Newton-Raphson method—a straightforward, efficient way to refine your guesses until you get close to the actual square root.
First, Let’s Refine Your Existing Code
Your current code hardcodes x=16 and g=9, which works for this specific case, but making them variables will let you reuse the code for any number. Plus, we’ll add logic to iteratively improve the guess.
How the Newton-Raphson Method Works for Square Roots
The core idea is simple: for any guess g, a better guess can be calculated using this formula:
new_g = (g + x / g) / 2
We repeat this calculation until the square of our guess is close enough to x (we’ll define "close enough" with a small value called epsilon, like 0.0001).
Full Step-by-Step Code
Here’s how to build out your algorithm with explanations:
# Algorithm for finding the square root of x x = 16 # Target number we want the square root of initial_guess = 9 g = initial_guess epsilon = 0.0001 # Controls how precise we want the result to be step = 1 # Print your initial step (matches what you already wrote!) print(f"Step {step}: The guess is {g} and its square is {g * g}") # Iterate to refine the guess while abs(g * g - x) > epsilon: step += 1 # Update the guess using the Newton-Raphson formula g = (g + x / g) / 2 # Print each step to see the guess improving print(f"Step {step}: The guess is {g:.4f} and its square is {g * g:.4f}") # Final result print(f"\nSuccess! The square root of {x} is approximately {g:.4f}")
Let’s Break This Down
- Variables:
xis your target number,gholds the current guess,epsilonsets how close we need to get to the actual square root (smaller = more precise). - Loop: The
whileloop keeps running until the difference betweeng²andxis smaller thanepsilon. - Guess Update: The formula
(g + x/g)/2averages the current guess andx/g—this pulls the guess closer to the real square root every time. - Print Statements: We keep track of each step so you can see how the guess gets better with each iteration.
Try These Next Steps
Since you’re new to Python, experiment with:
- Changing
xto non-perfect squares (like 2, 10, or 73) to see how the algorithm handles them. - Using different initial guesses (even a wild one like 100 for x=16!)—you’ll notice the algorithm still converges quickly.
- Adjusting
epsilon(e.g., 0.01 for less precision, 0.000001 for more) to see how it affects the number of steps.
内容的提问来源于stack exchange,提问作者Naseeb Hassan

