使用指定方法创建Python平方根求解函数时遇无输出问题的技术求助
Troubleshooting Your Square Root Function
Hey there! Let's figure out why your code isn't producing output and fix it up. I can see you're trying to implement a square root calculation (looks like a take on Newton-Raphson iteration), so let's break down the issues step by step:
Key Problems in Your Code
- Infinite Loop: Your
while Trueloop has no exit condition unless the exact check(int((temp+n)/2))**2 == numis met. For non-perfect squares (like 2, 3, 5), this condition will never trigger, so the loop runs forever without returning anything. - Overly Strict Termination Check: That integer cast and exact equality check only works for perfect squares. Most square roots are irrational, so we need a way to stop when our guess is "close enough" (using a precision threshold) instead of waiting for an exact match.
- Redundant Logic: The
if not num/n == ncheck is unnecessary—ifnum/n == n, thennis already the square root, and we can just return it immediately instead of proceeding with the temp variable dance.
Fixed Implementation
Here's a revised version of your function that addresses these issues, with comments explaining each change:
def findSquareRt(num): # Handle edge cases first to avoid errors if num < 0: return "Error: No real square root for negative numbers" if num == 0: return 0 n = 8 # Initial guess precision = 1e-6 # Define how close we need to be to the actual value while True: next_n = (n + num / n) / 2 # Core Newton-Raphson iteration step # Stop the loop when our guess is accurate enough if abs(next_n - n) < precision: return next_n # Update our guess for the next iteration n = next_n
How This Works
- Edge Case Handling: We first check for negative numbers (no real roots) and 0 (trivial case) to avoid runtime errors.
- Precision-Based Termination: Instead of waiting for an exact match, we stop when the difference between our current and next guess is smaller than
1e-6—you can adjust this value for more or less precision depending on your needs. - Simplified Iteration: The Newton-Raphson formula is streamlined to its core form, which converges quickly to the correct square root for any positive number.
Test It Out
Try these examples to see it in action:
print(findSquareRt(16))→ Returns4.0print(findSquareRt(2))→ Returns approximately1.41421356237print(findSquareRt(25))→ Returns5.0
内容的提问来源于stack exchange,提问作者LauJk_78
相关产品推荐
相关产品推荐

