MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / differentiate

Function differentiate

maths/dual_number_automatic_differentiation.py:95–128  ·  view source on GitHub ↗

>>> differentiate(lambda x: x**2, 2, 2) 2 >>> differentiate(lambda x: x**2 * x**4, 9, 2) 196830 >>> differentiate(lambda y: 0.5 * (y + 3) ** 6, 3.5, 4) 7605.0 >>> differentiate(lambda y: y ** 2, 4, 3) 0 >>> differentiate(8, 8, 8) Traceback (most rec

(func, position, order)

Source from the content-addressed store, hash-verified

93
94
95def differentiate(func, position, order):
96 """
97 >>> differentiate(lambda x: x**2, 2, 2)
98 2
99 >>> differentiate(lambda x: x**2 * x**4, 9, 2)
100 196830
101 >>> differentiate(lambda y: 0.5 * (y + 3) ** 6, 3.5, 4)
102 7605.0
103 >>> differentiate(lambda y: y ** 2, 4, 3)
104 0
105 >>> differentiate(8, 8, 8)
106 Traceback (most recent call last):
107 ...
108 ValueError: differentiate() requires a function as input for func
109 >>> differentiate(lambda x: x **2, "", 1)
110 Traceback (most recent call last):
111 ...
112 ValueError: differentiate() requires a float as input for position
113 >>> differentiate(lambda x: x**2, 3, "")
114 Traceback (most recent call last):
115 ...
116 ValueError: differentiate() requires an int as input for order
117 """
118 if not callable(func):
119 raise ValueError("differentiate() requires a function as input for func")
120 if not isinstance(position, (float, int)):
121 raise ValueError("differentiate() requires a float as input for position")
122 if not isinstance(order, int):
123 raise ValueError("differentiate() requires an int as input for order")
124 d = Dual(position, 1)
125 result = func(d)
126 if order == 0:
127 return result.real
128 return result.duals[order - 1] * factorial(order)
129
130
131if __name__ == "__main__":

Calls 3

factorialFunction · 0.90
DualClass · 0.85
funcFunction · 0.85

Tested by

no test coverage detected