python - 如何在给定的区间内使用牛顿法

标签 python sympy newtons-method

我可以使用牛顿法计算函数的根,方法是用新 x 值减去旧 x 值并检查收敛标准。当给定一个闭区间时,有没有办法做到这一点,例如

给定一个函数和区间 [a,b] = [0.1, 3.0],将通过检查 [3.0 - 0.1] < 0.000001,即 [b-a] < 0.000001 来计算收敛标准。

我提供的代码使用 x 值计算收敛标准。我试图弄清楚是否有办法可以使用间隔而不是 x 值。

from math import *

x = 1.0 #initial value

for j in range(1, 101):
    xnew = (x**2 + cos(x)**2 -4*x)/(2*(x - cos(x)*sin(x) -2))

    if abs(xnew - x) < 0.000001:
        break
    x = xnew

print('Root = %0.6f ' % xnew)
print('Number of iterations = %d' % j)

最佳答案

听起来你想保证在给定的时间间隔内找到根(这不是牛顿-拉夫森可以保证的)。您可以为此使用二分法。如果您知道函数在给定间隔内改变符号(并且在同一间隔内连续),则类似以下内容的工作原理:

>>> from sympy.abc import x
>>> from sympy import nsolve
>>> ivl = 0,3
>>> expr = (x**2 + cos(x)**2 -4*x)
>>> nsolve(expr, x, ivl)
0.250324492526265

但看起来您在尝试使用 NR 方法时可能会混淆一些变量。 xnew你计算的看起来非常像 f(x)/f'(x)这是 dxxnew = x - dx 。所以如果你写:

for j in range(1, 101):
  dx = (x**2 + cos(x)**2 -4*x)/(2*(x - cos(x)*sin(x) -2))
  if abs(dx) < 0.000001:
    break
  x = x - dx

print('Root = %0.6f ' % x)
print('Number of iterations = %d' % j)

你会得到

Root = 0.250324 
Number of iterations = 4

关于python - 如何在给定的区间内使用牛顿法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58783512/

相关文章:

python - 如何将字节保存为图像?

python - 未知的 python 表达式 filename=r'/path/to/file'

python - 使用函数创建 sympy 矩阵

python - 牛顿法 : order of statements in loop

c - 为什么这个 C 函数(求 n 的平方根的牛顿拉夫逊法)不能正常工作?

Python程序仍在运行但找不到PID

python - map 与列表;为什么会有不同的行为?

python - 将列表转换为序列以制作一个 sympy 多边形

python - 如何在sympy中为变量的下标写求和符号

c - 这个 C 习语是什么意思?