The sine derivative is not working as expected because sinus
converts the +h
part into radians, while the denominator leaves it in degrees. You'll notice that the following function calculates the derivative correctly.
# treat h as degrees
def derivative(func, x):
h = 0.0000000001
return (func(x + h) - func(x)) / radians(h)
derivative(sinus, 60) # 0.5000468070196941
Or, alternatively, the value of h
could be converted into degrees before passing it into sinus
.
# treat h as radians
def derivative(func, x):
h = 0.0000000001
return (func(x + degrees(h)) - func(x)) / h
derivative(sinus, 60) # 0.5000000413701855
Notice that the latter function produces a more precise value because a radian value of 0.00...01 is smaller than its corresponding degree value. However, both of these approaches will not work for functions that don't expect an argument in degrees.
The only way to address this issue is to specify whether the input is in degrees, and even this may not work for more complicated trigonometric equations (since powers of π/180 pop up when differentiating the equations when expressed in degrees).
def derivative(func, x, trans=lambda x: x):
h = 0.0000000001
return (func(x + trans(h)) - func(x)) / h
derivative(sinus, 60, degrees) # 0.5000000413701855