python 输入不断重复

niwlg2el  于 2022-12-02  发布在  Python
关注(0)|答案(1)|浏览(154)

你好,我是编程新手,我在为uni类编写牛顿方法,代码中用户输入f(x)的部分一直在重复。
这是我正在做的代码,它工作,但def f(x)保持重复2或3次之前,while开始

import math
import sympy as smp
from sympy import *
x = smp.symbols('x')
x0=float(input("Initial Value:"))
k=1
n=int(input("Number of interactions:"))
def f(x):
  return eval(input("f(x):"))
f_prime= smp.diff(f(x), x)
f_prime = lambdify(x, f_prime)
while(k<=n):
  r=x0-(f(x0)/f_prime(x0))
  print("root:",r,"interaction:",k)
  k=k+1
  x0=r
ymdaylpp

ymdaylpp1#

您可以执行以下代码。

代码

from sympy import Symbol, diff, sympify

def newton_method(func, sym, x0, n = 10):
    diff_func = diff(func, x)    # derivative of function
    
    root = x0
    for i in range(n):
        root = root - float(func.subs(x, root)/diff_func.subs(x, root))
        
    return root
   
# Setup
expression = input('input function: ')      # String expression corresponding to function
f = sympify(expression)                     # string expression to sympy function
x0 = float(input("Initial Value:"))        
n = int(input("Number of interactions:"))  

# Find root
root = newton_method(f, Symbol('x'), x0, n) # newton method with x as symbol

print('root:', root)

测试

input function:  x**2 - 2*x + 1
Initial Value: 0
Number of interactions: 10
root: 0.9990234375

相关问题