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

牛顿法Python实现遇TypeError:字符串与字符串不支持除法运算求助

Fixing "unsupported operand type(s) for /: 'str' and 'str'" in Newton Method Python Code

Hey there, let's break down what's causing this error and fix your Newton Method code.

The Root Cause

The error happens because input() returns strings by default, and your current f(x) and fprime(x) functions just return those raw strings instead of calculating their numeric value for the given x. When you try to do f(guess)/fprime(guess), you're attempting to divide two strings—an operation Python doesn't support, hence the TypeError.

Quick Fix Using eval()

For a simple, quick fix (great for personal scripts where you control the input), we can use eval() to turn the input strings into actual mathematical calculations. Here's the revised code:

# Get function and derivative expressions from user input
func_str = input("Write your function (use 'x' as the variable): ")
deriv_str = input("Input the derivative of your function (use 'x' as the variable): ")

def f(x):
    # Replace 'x' with the current value and evaluate the expression
    return eval(func_str.replace('x', str(x)))

def fprime(x):
    return eval(deriv_str.replace('x', str(x)))

guess = 1.0  # Use float to ensure decimal division behavior
for n in range(1, 100):
    nextguess = guess - f(guess)/fprime(guess)
    print(f"Iteration {n}: {nextguess}")
    
    # Optional: Stop early when we've converged to a root
    if abs(nextguess - guess) < 1e-6:
        print(f"Converged to root: {nextguess}")
        break
    guess = nextguess

Key changes here:

  • eval() converts the input string into a computed numeric value after replacing 'x' with the current guess.
  • We set guess = 1.0 (a float) to ensure division returns decimals instead of integers (though Python 3 handles this well by default, it's good practice).
  • Added a convergence check to exit the loop early once the guess stops changing significantly (no need to run all 100 iterations).

Safer Alternative with sympy

If you're concerned about the security risks of eval() (it can execute arbitrary code if given malicious input), use the sympy library for symbolic math parsing. It's designed safely for this use case.

First install sympy:

pip install sympy

Then use this code:

from sympy import symbols, sympify

# Create a symbolic variable for x
x = symbols('x')

# Safely parse input expressions into symbolic objects
func = sympify(input("Write your function (use 'x' as the variable): "))
deriv = sympify(input("Input the derivative of your function (use 'x' as the variable): "))

def f(val):
    # Substitute the symbolic x with a numeric value and convert to float
    return float(func.subs(x, val))

def fprime(val):
    return float(deriv.subs(x, val))

guess = 1.0
for n in range(1, 100):
    nextguess = guess - f(guess)/fprime(guess)
    print(f"Iteration {n}: {nextguess}")
    
    if abs(nextguess - guess) < 1e-6:
        print(f"Converged to root: {nextguess}")
        break
    guess = nextguess

This version uses sympify() to safely parse mathematical expressions without executing arbitrary code, making it better for scenarios where input might come from untrusted sources.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:02:11