【发布时间】:2018-03-09 11:06:33
【问题描述】:
我正在做这个任务:
首先,实现 f(x)= exp(x)-sin(x) 最接近零定义的 f 函数。
其次,在给定输入值 x0 = -3.5 和 x1 = -2.5 的情况下,实现第 95 页的 Secant 方法并使用它找到 f 函数的根
添加以下内容
- 绝对测试:abs(f(x) ) - 相对测试:abs(x^k - x^{k-1})/ abs(x^{k}) \leq delta
- 最大迭代保护:k在每次迭代中打印出迭代次数k、当前根值和当前f值。打印 20 位浮点数。
这是我必须完成的代码:
import numpy as np
from math import exp, sin
import matplotlib.pyplot as plt
def f(x: float) -> float:
return
def secant(x0: float, x1: float, f, epsilon: float, delta: float, iter_max: int) -> float:
return
这是第 95 页的伪代码:
input: x_0, x_1, delta, epsilon, iter_max
fx_0 <- f(x_0); fx_1 <- f(x_1)
output: 0, x_0, fx_0
output: 1, x_1, fx_1
for k = 2 to iter_max do
if |fx_0| > |fx_1| then
x_0 <-> x_1; fx_0 <-> fx_1
end if
s <- (x_1 - x_0) / (fx_1 - fx_0)
x_1 <- x_0
fx_1 <- fx_0
x_0 <- x_0 - fx_0 * s
fx_0 <- f(x_0)
output: k, x_0, fx_0
if |fx_0| < epsilon or |x_1 - x_0| < delta then stop
end do
这是我自己的尝试:
def f(x: float) -> float:
return exp(x) - sin(x) == 0
def secant(x0: float, x1: float, f, epsilon: float, delta: float, iter_max: int) -> float:
fx0 = f(x0)
fx1 = f(x1)
return 0, x0, fx0
return 1, x1, fx1
for k in range(2, iter_max):
if abs(fx0) > abs(fx1):
x0 = x1
x1 = x0
fx0 = fx1
fx1 = fx0
s = (x1 - x0) / (fx1 - fx0)
x1 = x0
fx1 = fx0
x0 = x0 - fx0 * s
fx0 = f(x0)
return k, x0, fx0
if abs(fx0) < epsilon or abs(x**k - x**(k - 1))/ abs(x**(k)) <= delta:
break
如果我遵循我的代码
root = secant(-3.5, -2.5, f, 0.00000000001, 0.000001, 10)
print(root)
我得到:(0,-3.5,假)。所以它实际上并没有做任何迭代。我该如何解决?
【问题讨论】:
-
您的问题是什么?您有问题或错误吗?
-
如果你使用 return 你将不会在你的函数中执行以下行
-
如果您使用 silly return,您的 sec 割线代码将减少为以下内容。:
def secant(x0: float, x1: float, f, epsilon: float, delta: float, iter_max: int) -> float: fx0 = f(x0) fx1 = f(x1) return 0, x0, fx0 -
抱歉含糊不清。我的问题是输出。例如,如果我使用
root = secant(-3.5, -2.5, f, 0.00000000001, 0.000001, 10) print(root)跟随我的代码,我会得到:(0, -3.5, False)。所以它实际上并没有进行任何迭代。 -
将退货更改为印刷品
标签: python pseudocode numerical-methods