我试图解决以下问题。我尝试首先使用 0.1 设置步长 h 来解决它。但是我需要在我的代码中更改它并使用 for 循环遍历值 0,1,..,20。我有点困惑如何解决这个问题,但我希望能得到一些帮助来修复我到目前为止生成的代码。谢谢!
import numpy as np
from math import sin
def derivative(func , x, h ):
for h in range(20):
return (func(x+h)-func(x))/h
def f(x):
return sin(x)
print(derivative(f, pi/4))
给出输出
0.6706029729039897
我的编辑:
def derivative(func , x, h ):
for h in range(20):
return (func(x+h)-func(x))/h
请您参考如下方法:
该练习要求您使用不同的精度(使用变量 h 表示)计算导数,并将其与函数的精确/实数导数进行比较。
令 h = 10 ^ -j,其中 j 从 0 到 20 不等。这意味着 h 将(离散地)从 10⁻⁰ 到 10⁻²⁰。您可以为此使用 for 循环和 range(...) 函数。然后将其传递给 derivative 函数(您可以将第三个参数作为 h 的值)
def derivative(func, x, h):
return (func(x + h) - func(x)) / h
接下来,您需要将其与精确 导数进行比较。函数 f(x) = sin(x) 有一个已知的(精确的)导数,即 cos(x)。在数学符号中,d(sin x)/dx = cos x。这意味着对于任何 x,cos(x) 将为您提供 sin 在该 x 处的精确导数.
因此您需要将 derivative(...) 函数的结果与 cos(x) 的值进行比较。这会给你带来不同。然后,您可以使用基本的 Python 函数 abs(x) 来获取该差值的绝对值,这将为您提供绝对差值,这就是所需的结果。对从 0 到 20 的每个 j 执行此操作,并将结果存储在某个地方,数组或字典中。
from math import sin, cos, pi
x = pi / 4
diffs = {}
for j in range(21): # range is exclusive so range(21) will stop at 20
h = 10 ** -j
deriv = derivative(sin, x, h)
exact = cos(x)
diff = abs(deriv - exact)
diffs[h] = diff
然后,您可以使用 pyplot 的 loglog 函数将这些结果绘制在图表上,将 range(...) 结果作为 X 传递,将包含的数组作为 Y 传递结果。
import matplotlib.pyplot as plt
ordered = sorted(diffs.items())
x, y = zip(*ordered)
plt.loglog(x, y)
