From cb3915b405aa67450ac2ebed5062c4bd1684b3c0 Mon Sep 17 00:00:00 2001 From: Daniel Heras Quesada Date: Sun, 16 Nov 2025 19:23:59 +0100 Subject: [PATCH] feat: chain rule --- src/main.py | 17 ++++++++++++++++- src/modules/math.py | 11 +++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/main.py b/src/main.py index 8dadd26..fadbf60 100644 --- a/src/main.py +++ b/src/main.py @@ -1,8 +1,10 @@ from sympy import diff, limit, oo, symbols from modules.math import ( - t_build_partial_derivate, t_build_derivate, + t_build_derivative_from_limit, + t_build_partial_derivate, + t_calculate_derivative_limit, t_calculate_e, t_calculate_e_limit, t_compound_interest, @@ -37,4 +39,17 @@ if __name__=="__main__": partial_derivative_y = t_build_partial_derivate((3 * y ** 3) + 2 * z ** 2, y) partial_derivative_z = t_build_partial_derivate((3 * y ** 3) + 2 * z ** 2, z) print(partial_derivative_y, partial_derivative_z) + print(t_build_derivative_from_limit(x ** 2)) + print(t_calculate_derivative_limit(x ** 2, 2)) + ## Chain rule + # for a given function y (lets say y = x ** 2 + 1) and another z (lets say z = y ** 3 - 2), we can find a derivativeof z with respect to x by multiplying the derivatives + # normal derivative calc + x = symbols("x") + z = (x ** 2 + 1) ** 3 - 2 + print(t_build_derivate(z)) + # chain rule calc + x, y, z = symbols("x y z") + y_f = x ** 2 + 1 + z_f = y ** 3 - 2 + print(t_build_derivate(y_f), t_build_derivate(z_f)) diff --git a/src/modules/math.py b/src/modules/math.py index ac8785e..475affd 100644 --- a/src/modules/math.py +++ b/src/modules/math.py @@ -55,6 +55,17 @@ def t_calculate_e_limit(): def t_calculate_derivative(f, x, step_size): return (f(x + step_size) - f(x)) / (x +step_size - x) +def t_build_derivative_from_limit(f): + x, s = symbols("x s") + slope_f = (f.subs(x, x + s) - f) / (x + s - x) # Slope function + return limit(slope_f, s, 0) + +def t_calculate_derivative_limit(f, x_target): + x = symbols("x") + slope_f = t_build_derivative_from_limit(f) + return slope_f.subs(x, x_target) + + def t_build_derivate(f): return diff(f)