我正在研究一个项目,我试图改变我在网上找到的衍生函数。
我打算创建一个函数,证明导数为x
接近0
,这就是我所拥有但我想循环它以使h值改变:
#derivative calc
def f(x):
return x**2
def derivative(x):
h = .001
rise = f(x+h)-f(x)
run = h
slope = rise/run
return slope
z=int(input("please enter value of x:"))
a=derivative(z)
print(a)
def f(x):
return x**2
def derivative(x):
h = .0001
rise = f(x+h)-f(x)
run = h
slope = rise/run
return slope
z=int(input("please enter value of x:"))
a=derivative(z)
print(a)
def f(x):
return x**2
def derivative(x):
h = .00001
rise = f(x+h)-f(x)
run = h
slope = rise/run
return slope
z=int(input("please enter value of x:"))
a=derivative(z)
print(a)
def f(x):
return x**2
def derivative(x):
h = .000001
rise = f(x+h)-f(x)
run = h
slope = rise/run
return slope
z=int(input("please enter value of x:"))
a=derivative(z)
print(a)
def f(x):
return x**2
def derivative(x):
h = .0000001
rise = f(x+h)-f(x)
run = h
slope = rise/run
return slope
z=int(input("please enter value of x:"))
a=derivative(z)
print(a)
答案 0 :(得分:2)
这似乎是家庭作业,所以我只是给你一个提示:
如果您想改变h
,请将其作为该函数的参数。
因此,您的代码应如下所示:
def derivative(x,h):
#body of your function, slightly modified
当你在它时,让f
本身成为一个参数,这样相同的代码就可以在数字上区分不同的功能,而不管它们的名称是什么。所以你的定义可以开始:
def derivative(f,x,h):
#body of your function, slightly modified
然后,您可以使用for循环遍历各种h
。例如,以下循环"证明" sin(x)
在0的导数是1:
for n in range(5):
h = 10**-n
print("h =",h,"=>",derivative(math.sin,0,h))
输出(一旦derivative
已正确定义):
h = 1 => 0.8414709848078965
h = 0.1 => 0.9983341664682815
h = 0.01 => 0.9999833334166665
h = 0.001 => 0.9999998333333416
h = 0.0001 => 0.9999999983333334
就您的其他代码而言 - 为什么假设x
是int
?因为你正在进行浮点运算,所以最好使它成为一个浮点数。因此,您的输入行应该看起来更像
z=float(input("please enter value of x:"))