如何用Python求解含三个3D方程的非线性方程组
Hey there! Let's break down how to find the intersection points (solutions) of your three 3D equations using Python. First, let's restate your equations clearly to make coding easier:
Equation 1:
-0.006683x² - 0.06893x + 56.73 - z = 0
Equation 2:0.002538y² - 1.115y + 56.73 - z = 0
Equation 3:(x-24.680)² + (y-238.341)² + (z+13.971)² = 12.580²
Step 1: Pick the Right Tool
For solving nonlinear systems like this, Python's scipy.optimize module is perfect. We'll use fsolve here—it's straightforward and works well for this type of problem.
Step 2: Define the Residual Function
We need a function that takes a vector [x, y, z] and returns how far each equation is from 0 (called "residuals"). The solver will tweak x, y, z until all residuals are nearly zero.
Step 3: Choose a Reasonable Initial Guess
Nonlinear solvers need a starting point. Let's think about the geometry:
- The first two equations are parabolic surfaces, so z is determined by x (eq1) and y (eq2) respectively.
- The third equation is a sphere centered at
(24.680, 238.341, -13.971)with radius 12.580, so z should be between ~-26.55 and ~-1.39.
A good initial guess might be [0, 200, -10]—close to the sphere's center, with z in the sphere's valid range.
Full Code Example
Here's the complete, commented code:
import numpy as np from scipy.optimize import fsolve # Define the system of equations as a residual function def equations(vars): x, y, z = vars # Calculate how far each equation is from 0 eq1 = -0.006683 * x**2 - 0.06893 * x + 56.73 - z eq2 = 0.002538 * y**2 - 1.115 * y + 56.73 - z eq3 = (x - 24.680)**2 + (y - 238.341)**2 + (z + 13.971)**2 - 12.580**2 return [eq1, eq2, eq3] # Initial guess for x, y, z initial_guess = [0, 200, -10] # Solve the system solution = fsolve(equations, initial_guess) # Extract the solution values x_sol, y_sol, z_sol = solution print("Found solution:") print(f"x = {x_sol:.4f}") print(f"y = {y_sol:.4f}") print(f"z = {z_sol:.4f}") # Verify the solution (residuals should be very close to 0) print("\nVerification (residuals):") residuals = equations(solution) print(f"Equation 1 residual: {residuals[0]:.6f}") print(f"Equation 2 residual: {residuals[1]:.6f}") print(f"Equation 3 residual: {residuals[2]:.6f}")
Notes on Finding All Possible Solutions
Nonlinear systems can have multiple solutions (up to 4 in this case, given the geometry). If you don't get a valid solution, or want to find all intersections:
- Try different initial guesses (e.g.,
[50, 250, -20]or[-10, 220, -5]). - If
fsolvestruggles, usescipy.optimize.rootwith alternative methods like'lm'(least squares) for more robustness.
内容的提问来源于stack exchange,提问作者Diogo Mata

