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

如何用Python求解无法将目标变量移到单侧的不可解方程?

Hey, great question! This is exactly the kind of transcendental equation that doesn't have an analytical solution (meaning you can't rearrange it to get x all by itself on one side), so we need to use numerical methods to find an approximate solution. Let's walk through how to solve your example sqrt(x) = (a/13)*log(b/x²) in Python, step by step.

Step 1: Rewrite the equation for numerical solving

Numerical root-finders work by finding where a function f(x) = 0. So let's rearrange your equation to get everything on one side:
13*sqrt(x) - a*log(b/x²) = 0
I multiplied both sides by 13 to avoid fractions, which makes calculations cleaner, but you could also use sqrt(x) - (a/13)*log(b/x²) = 0—either works.

Step 2: Use scipy.optimize for numerical root finding

The scipy library has excellent tools for this. For single-variable equations like yours, root_scalar is the go-to function (it's designed specifically for this case, unlike the more general root function for multi-variable systems).

First, let's write code that defines our equation, sets known values for a and b, and finds the solution:

import math
from scipy.optimize import root_scalar

# Define our f(x) = 0 function
def equation(x, a, b):
    # Make sure x is positive (since sqrt(x) and log(b/x²) require x > 0)
    if x <= 0:
        return float('inf')  # Return a large value if x is outside valid domain
    return 13 * math.sqrt(x) - a * math.log(b / (x**2))

# Let's pick example known values for a and b (replace these with your actual values)
a = 10
b = 100

# First, we need to find an interval [x_low, x_high] where f(x) changes sign
# This tells the solver there's a zero between these points. Let's test some values:
print(f"f(0.1) = {equation(0.1, a, b)}")  # Negative value
print(f"f(1) = {equation(1, a, b)}")      # Positive value
# Perfect, the sign changes between 0.1 and 1, so we use this interval

# Solve using the Brentq method (robust and efficient for single-variable roots)
result = root_scalar(equation, args=(a, b), method='brentq', bracket=[0.1, 1])

# Check if the solver succeeded
if result.converged:
    x_solution = result.root
    print(f"Found solution: x = {x_solution:.4f}")
    
    # Verify the solution to make sure it works
    lhs = math.sqrt(x_solution)
    rhs = (a/13) * math.log(b / (x_solution**2))
    print(f"Verification: sqrt(x) = {lhs:.4f}, (a/13)*log(b/x²) = {rhs:.4f}")
else:
    print(f"Solving failed: {result.flag}")

Step 3: How to choose the right interval/initial guess

If you're not sure where to pick your interval, plot the function to visualize where it crosses zero. Here's how to do that with matplotlib:

import matplotlib.pyplot as plt
import numpy as np

# Generate x values in the valid domain (x > 0)
x_vals = np.linspace(0.01, 5, 100)
y_vals = [equation(x, a, b) for x in x_vals]

# Plot the function and the y=0 line (where the root is)
plt.plot(x_vals, y_vals, label=r'$f(x) = 13\sqrt{x} - a\log\left(\frac{b}{x^2}\right)$')
plt.axhline(y=0, color='red', linestyle='--', label='y=0 (Root location)')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.grid(True)
plt.show()

This plot will show you exactly where the function crosses zero, making it easy to pick a valid interval for the solver.

Alternative: Using root for multi-variable (but works for single too)

If you already use root for other problems, you can adapt it for this single-variable case by wrapping x in a list:

from scipy.optimize import root

def equation_multi(x, a, b):
    return [13 * math.sqrt(x[0]) - a * math.log(b / (x[0]**2))]

initial_guess = [0.5]  # A starting guess near the expected solution
result = root(equation_multi, initial_guess, args=(a, b))

if result.success:
    print(f"Solution: x = {result.x[0]:.4f}")
else:
    print(f"Failed: {result.message}")

Key Notes

  • Domain matters: Your equation is only valid for x > 0 and b > 0 (since we're taking the log of b/x²). Make sure your input values respect this.
  • Initial guess/interval: The solver needs a starting point or interval where a root exists. If you pick a bad interval (where f(x) doesn't change sign), it won't find a solution. Plotting the function is the easiest way to avoid this.
  • Verification: Always check that the solution satisfies the original equation—numerical solvers can sometimes return values that are close but not perfect, so verifying ensures you got a good result.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 06:58:32