如何用Python求解含两变量乘积的联立方程(x=ab,n=a+b)?
Hey, let's tackle your two Python equation-solving questions with clear, practical solutions:
Since these are nonlinear equations (thanks to the variable product term), you can't use linear algebra methods directly. Instead, numerical root-finding tools work perfectly here. The scipy.optimize module has functions like fsolve that handle this seamlessly.
Let's use a concrete example to demonstrate. Suppose we have this system:
x + y = 7
x*y = 12
Here's how to solve it in Python:
from scipy.optimize import fsolve # Define the system as a function that returns residuals (should be 0 at solution) def system(vars): x, y = vars # Rewrite equations to equal zero eq1 = x + y - 7 eq2 = x * y - 12 return [eq1, eq2] # Start with an initial guess (adjust based on your problem's context) initial_guess = [1, 1] # Run the solver x_sol, y_sol = fsolve(system, initial_guess) # Print and verify the solution print(f"Solution: x = {x_sol:.2f}, y = {y_sol:.2f}") print(f"Check first equation: {x_sol + y_sol:.2f} = 7? {abs(x_sol + y_sol -7) < 1e-6}") print(f"Check second equation: {x_sol * y_sol:.2f} = 12? {abs(x_sol * y_sol -12) < 1e-6}")
A few notes:
- The initial guess matters! If your system has multiple solutions, the solver will converge to the one closest to your guess.
- For integer solutions, you can round the results and verify, but numerical methods work for real-number solutions too.
- If you don't have
scipyinstalled, runpip install scipyfirst.
This is a classic problem that translates directly to a quadratic equation. Here's the trick: if a + b = n and a*b = x, then a and b are roots of the quadratic equation t² - n*t + x = 0. Using the quadratic formula:
a = (n + sqrt(n² - 4x)) / 2
b = (n - sqrt(n² - 4x)) / 2
For a and b to be integers, two conditions must hold:
- The discriminant
D = n² - 4xmust be a perfect square. n ± sqrt(D)must be even (so dividing by 2 gives an integer).
Python handles large integers natively, so no issues with big numbers here. Here's the code:
import math def find_integer_pair(x, n): discriminant = n**2 - 4 * x if discriminant < 0: return None # No real solutions, let alone integers # Compute integer square root (avoids floating point errors for big numbers) sqrt_d = math.isqrt(discriminant) if sqrt_d * sqrt_d != discriminant: return None # Discriminant isn't a perfect square # Check if numerators are even if (n + sqrt_d) % 2 != 0 or (n - sqrt_d) % 2 != 0: return None a = (n + sqrt_d) // 2 b = (n - sqrt_d) // 2 # Return sorted pair for consistency (optional) return (max(a, b), min(a, b)) # Test with large integers x = 12345678901234567890 n = 1234567890123456789 + 9876543210987654321 pair = find_integer_pair(x, n) if pair: a, b = pair print(f"Found integers: a = {a}, b = {b}") print(f"Verify a*b = x? {a*b == x}") print(f"Verify a+b = n? {a+b == n}") else: print("No integer solutions exist for the given x and n.")
Key points:
- Use
math.isqrt(Python 3.8+) instead ofint(math.sqrt())—it's designed for integers and avoids precision loss with huge numbers. - The function returns
Noneif no valid integer pairs exist, so make sure to handle that case in your code.
内容的提问来源于stack exchange,提问作者Ananay Gupta

