我想使用导数的定义找到函数(x)(x - 1)的导数。我希望我的增量为1e-2
。这样它就可以模拟限制为零。我在Range for Floats上看到我可以使用用户定义的函数来创建带浮点变量的范围函数。
def frange(x, y, jump):
while x < y:
yield x
x += jump
def drange(start, stop, step):
r = start
while r < stop:
yield r
r += step
i = frange(1e-14,1e-2,2)
for k in i:
set = []
x = 1
dvt = ((x + k ) * (x + k - 1) - x*(x - 1))/k
set.append(dvt)
print(set)
当我运行程序时,我只得到
[0.9992007221626509]
发生了什么我没有在列表中添加多个衍生物?
答案 0 :(得分:1)
设置你说
x += jump
这将x的值设置为2 + 1e-14,其大于1e-2
当我阅读代码时,似乎您可能意味着
myjump = pow(10, jump) #outside the loop
x *= myjump # inside the loop
这将在示例中将每个循环乘以100,并且过程1e-14,1e-12,1e-10 ... 1e-2
或者,如果您想添加它,那么您应该说
x += myjump # inside the loop
或者你需要测试跳跃实际上是一个小到足以被处理的分数。
答案 1 :(得分:0)
这是一个清理版本:
def fn(x):
return x * (x - 1)
def numerical_diff(fn, x, delta):
return (fn(x + delta) - fn(x)) / delta
def geometric_series(a, r, n):
value = a
for i in range(n):
yield value # a * r ** i
value *= r
def main():
x = 1.
for delta in geometric_series(0.01, 0.01, 7):
print(
"x = {:5.3f} f(x) = {:5.3f} delta = {:16.14f} f'(x) = {:16.14f}"
.format(x, fn(x), delta, numerical_diff(fn, x, delta))
)
if __name__ == "__main__":
main()
产生
x = 1.000 f(x) = 0.000 delta = 0.01000000000000 f'(x) = 1.01000000000000
x = 1.000 f(x) = 0.000 delta = 0.00010000000000 f'(x) = 1.00009999999989
x = 1.000 f(x) = 0.000 delta = 0.00000100000000 f'(x) = 1.00000099991773
x = 1.000 f(x) = 0.000 delta = 0.00000001000000 f'(x) = 1.00000000392253
x = 1.000 f(x) = 0.000 delta = 0.00000000010000 f'(x) = 1.00000008284037
x = 1.000 f(x) = 0.000 delta = 0.00000000000100 f'(x) = 1.00008890058334
x = 1.000 f(x) = 0.000 delta = 0.00000000000001 f'(x) = 0.99920072216265