def test_doitdoit(): done = Derivative(f(x, g(x)), x, g(x)).doit() assert done == done.doit()
def backward(f, x, h): return (f(x) - f(x - h)) / h def center(f, x, h): return (f(x + h) - f(x - h)) / (2 * h) x = Symbol('x') function = x**4 - 3 * x**3 + 6 * x**2 - 10 * x - 9 deriv1 = Derivative(function, x) deriv1_result = deriv1.doit().subs({x: 0}) deriv2 = Derivative(deriv1, x) deriv2_result = deriv2.doit().subs({x: 0}) print("exact: ", deriv1_result, deriv2_result) fir05 = derivative1(f, 0, 0.5) sec05 = derivative2(f, 0, 0.5) fir025 = derivative1(f, 0, 0.25) sec025 = derivative2(f, 0, 0.25) fir0125 = derivative1(f, 0, 0.125) sec0125 = derivative2(f, 0, 0.125) print("first derivtive:", fir05, "second derivative:", sec05) print("first derivtive:", fir025, "second derivative:", sec025)
# python 3.6 from sympy import Symbol, sin, Derivative x = Symbol('x') y = sin(x**2) * x d = Derivative(y, x) print(d.doit())
def test_issue_15893(): f = Function('f', real=True) x = Symbol('x', real=True) eq = Derivative(Abs(f(x)), f(x)) assert eq.doit() == sign(f(x))
def test_doitdoit(): done = Derivative(f(x, g(x)), x, g(x)).doit() assert done == done.doit()
x = Symbol('x') # Given the Initial Conditions. fx = x**3 - 6 * x**2 + 11 * x - 6 x_gvn = 0.5 h = 0.5 # ---------------------------------------------- x_plus_h = x_gvn + h x_minus_h = x_gvn - h # --------------------------------------------- deriv = Derivative(fx, x) dfx = deriv.doit() # Derivative of F(x) print("\nF'(x) =", dfx) dfx_true_value = float(dfx.subs({x: x_gvn})) # Substituting the value in F'(x). print("True Value of F'(x) =", dfx_true_value) fx_value = float(fx.subs({x: x_gvn})) # f(x) value print("\nF(x) = F(", x_gvn, ") =", fx_value) fx_plus_h = float(fx.subs({x: x_plus_h})) # f(x+h) value print("F(x+h) = F(", x_plus_h, ") =", fx_plus_h) fx_minus_h = float(fx.subs({x: x_minus_h})) # f(x-h) value print("F(x-h) = F(", x_minus_h, ") =", fx_minus_h)
from sympy import Symbol, Derivative x = Symbol('x') function = -5 * x**2 + 10 * x + 4 d = Derivative(function, x) res = d.doit().subs({x: 3}) print(res)
# in centimeters. What is the velocity of the particle when t = 1? Ft = (t + 3)**.5 t = Symbol('t', positive=True) Dt = Derivative(Ft, t).doit() Dt = Dt - 1 sln = solve(Dt, t) pprint(sln) # 3.3.6 # Suppose f(x) = sqrt( x^2 + 5 ). # Find the equation of the line tangent to f(x) at ( -2, 3 ). x = Symbol('x', positive=True) Fx = (x**2 + 5)**.5 Fx d = Derivative(Fx, x) d Dx = d.doit() Dx m = solve(d - 2, x) m x, y, m = symbols('x, y, m') line = m * (x + 2) - y + 3
def turunan(pers): x = Symbol('x') deriv = Derivative(pers, x) return str(deriv.doit())
def f_deriv(value): x = Symbol('x') deriv = Derivative(f(x), x) return deriv.doit().subs({x: value})
def take_derivative(self): deriv = Derivative(self.function, x) return deriv.doit()
out_h2 = sigmoid(net_h2) net_o1 = out_h1 * w[4] + w[5] * out_h2 + b[1] out_o1 = sigmoid(net_o1) a = out_o1 net_o2 = out_h2 * w[7] + w[6] * out_h1 + b[1] out_o2 = sigmoid(net_o2) Eo1 = ((out_o1 - o[0])**2) / 2 Eo2 = ((out_o2 - o[1])**2) / 2 Etot = Eo1 + Eo2 from sympy import symbols, diff, solve from sympy import Symbol, Derivative out_o1 = Symbol('out_o1') f = ((out_o1 - o[0])**2) / 2 deriv = Derivative(f, out_o1) d = deriv.doit().subs({out_o1: a}, {o[0]: c}) p1 = 1 / (1 + math.exp(-net_o1)) p2 = p1 * (1 - p1) net_o1, w[4] = symbols('net_o1 w[4]', real=True) f = out_h1 * w[4] + w[5] * out_h2 + b[1] p3 = diff(f, w[4])
def derivative(f): x = Symbol('x') derivative = Derivative(f, x) return derivative.doit()
from sympy import Symbol, Derivative import sympy as sym import math x = Symbol('x') gx = x**3 - 4 # Giving G(x) function. deriv = Derivative(gx, x) dgx = deriv.doit() # Derivative of G(x) print("derivative of G(x)=", dgx) value = 1 / 2 approx = float(dgx.subs({x: value})) # Substituting the value in G'(x). print("g'(x) =", approx) for i in range(13): print('---------iteration', i + 1, '-----------') ans = gx.subs({x: value}) print("answer=", float(ans)) value = ans
''' Finding the Derivative of Functions ''' from sympy import Symbol, Derivative t = Symbol('t') St = 5 * t**2 + 2 * t + 8 # Find the value of the Derivative d = Derivative(St, t) print(Derivative(St, t), '=', d.doit()) # Substitute a value print(d.doit().subs({t: 1}))
from sympy import Symbol, Derivative t = Symbol('t') St = 5 * t**2 + 2 * t + 8 d = Derivative(St, t) d.doit() d.doit().subs({t: 1}) x = Symbol('x') f = (x**3 + x**2 + x) * (x**2 + x) Derivative(f, x).doit()
print( "We will find the min locations fx = 5x^4 - 22.4x^3 + 15.85272x^2 + 24.161472x - 23.4824832" ) print("What method do you want?") print("Using first and second derivatives : 1, Using approximation : 2") c = int(input("Your Choice : ")) #Using first and second derivatives if c == 1: print("Your choice is Using derivatives") init = float(input("Input initial value : ")) x = symbols('x') fx = 5 * x**4 - 22.4 * x**3 + 15.85272 * x**2 + 24.161472 * x - 23.4824832 fd = Derivative(fx, x) fdev = fd.doit() sd = Derivative(fdev, x) sdev = sd.doit() while True: f1 = fdev.subs({x: init}) f2 = sd.doit().subs({x: init}) if f1 == 0: print("The min location is : ", init) break elif f1 != 0: nv = init - 2 * (f1 / f2) dx = abs(nv - init) / 2 nv = nv + dx print(nv) if abs(f1) < 0.00000001: print("The min location is : ", init)
#!/usr/bin/env python # coding: utf-8 # In[1]: from sympy import init_printing, symbols, Integral, Derivative, sin, exp, Eq from IPython.display import display init_printing(use_latex=True, latex_mode='equation*') x = symbols('x') # In[2]: int_x = Integral(sin(x)*exp(x), x) display(Eq(int_x, int_x.doit())) derv_x = Derivative(sin(x)*exp(x), x) display(Eq(derv_x, derv_x.doit()))
def test_issue_15893(): f = Function('f', real=True) x = Symbol('x', real=True) eq = Derivative(Abs(f(x)), f(x)) assert eq.doit() == sign(f(x))
def calc_cumulant(self, _fun, direction, order): cgf = ln(_fun) deriv = Derivative(cgf, (direction, order)) all_terms = deriv.doit() all_terms = simplify(all_terms) return all_terms
def df(xi): x = Symbol('x') func = f(x) deriv = Derivative(func, x) return float(deriv.doit().subs({x: xi}))
def make_derivatives(derivatives): return np.array([[eval(str(d))] for d in derivatives]) function = raw_input("\nEscribe tu funcion: ") matched_variable = re.findall(r"x\d", function) variables = sorted(list(set(matched_variable))) derivatives = [] for var in variables: x = Symbol(var) partialderiv= Derivative(function, x) derivatives.append(partialderiv.doit()) exec('{} = 0.1'.format(var)) f2 = 1 alfa = 0 gradient = None S = [[0] for d in derivatives] counter = 0 while not (sqrt(f2) <= 0.0001): counter += 1 for i in range(len(variables)): exec("x{} += alfa * S[{}][0]".format(i+1, i)) gradient = numpy_fillna(make_derivatives(derivatives))
# -*- coding: utf-8 -*- """ @author: Nitin """ #The program aims at solving curves using Newton-Raphson method upto 2 places of decimal from sympy import Symbol, Derivative print( "This code is for polynomial expressions only. Do not enter functions like logarithms" ) x = Symbol('x') fun = eval(input("Enter the function here: ")) der = Derivative(fun, x) df = der.doit() print("\nThe function you've entered is: ", fun) print("\nThe derivative of the function is: ", df) def value( f, a): #function to determine value of a given function at a given point t = f.replace(x, a) return t def dec(a, b): #function to compare two given numbers upto 3 places of decimal m = str(a - int(a)) n = str(b - int(b)) if m[2:5] == n[2:5]: return True else: return False
import math import sympy from sympy import Symbol , Limit, S, Derivative t = Symbol('t') St = 5*t**2 + 2*t +8 print("St .{0}".format(St)) print(Derivative(St,t)) d = Derivative(St,t) print(d.doit()) print(d.doit().subs({t:1}))
Return basis function. """ return x**i x = Symbol("x") q = input("Enter the value of q [3]: ") y0 = input("Enter the value of y0 [0]: ") basis = [x**i for i in range(q+1)] ci = [Symbol("ci_%i" %i) for i in range(q+1)] y = y0 + sum(ci[i]*basis[i] for i in range(1,q+1)) print("The trial solution is: ", u) k = Matrix([[0,0,0],[0,0,0],[0,0,0]]) f = Matrix(1, q, range(q)) for i in range(1,q+1): for j in range(1,q+1): k[i-1,j-1] = ci[i]*ci[j]*np.diff(basis[i], x)*np.diff(basis[j], x) for i in range(1,q+1): f[i-1]=2*x*ci[i]*basis[i]+ci[i] functional= i ntegrate(sum(k.reshape(1,q**2))+sum(f),[x,0,1]) s1 = Derivative(functional,ci[1]) d1 = s1.doit() s2 = Derivative(functional,ci[2]) d2 = s2.doit() s3 = Derivative(functional,ci[3]) d3 = s3.doit() xx = solve([d1,d2,d3],dict=True) yt = y.subs(xx) print("The Approximate Solution is: yt= ",yt) xr = np.linspace(0,1,100) yt = xr**3/6 - xr # The Approximate Solution
MAX_X = 10 NUM_INPUTS = 50 noise = numpy.random.normal(size=NUM_INPUTS) x1 = numpy.random.uniform(low=MIN_X, high=MAX_X, size=(NUM_INPUTS, 1)) data = [] for num in range(NUM_INPUTS): data.append([x1[num][0], 0.3 * x1[num][0] + 1 + noise[num]]) f = ((data[0][0] * m + b) - data[0][1])**2 for num in range(1, NUM_INPUTS): f += ((data[num][0] * m + b) - data[num][1])**2 parderiv_m = Derivative(f, m) parderiv_b = Derivative(f, b) parderiv_m.doit() parderiv_b.doit() for i in range(0, 3): if (parderiv_m.doit().as_coeff_add()[1][i].as_coeff_Mul())[1] == 1: coeffecient1m = ( parderiv_m.doit().as_coeff_add()[1][i].as_coeff_Mul())[0] for i in range(0, 3): if (parderiv_m.doit().as_coeff_add()[1][i].as_coeff_Mul())[1] == m: coeffecientmm = ( parderiv_m.doit().as_coeff_add()[1][i].as_coeff_Mul())[0] for i in range(0, 3): if (parderiv_m.doit().as_coeff_add()[1][i].as_coeff_Mul())[1] == b: coeffecientbm = ( parderiv_m.doit().as_coeff_add()[1][i].as_coeff_Mul())[0] for i in range(0, 3):
def newton(): print(""" Newton Method """) # Ask user for the equation, interval, requiredDecimalPlaces # Get the equation equation = str(input("Enter the root equation: ")) # Get the requiredDecimalPlaces requiredDecimalPlaces = int( input("Please enter the required decimal places: ")) # Prepare the equation to fit derivative shape (** instead of ^ ) derv_equation = get_unparsed_equation(equation) # Get the first and the second derivative x = Symbol('x') # Variable first_derivative = Derivative(derv_equation, x) second_derivative = Derivative(first_derivative.doit(), x) # Select interval guess0 = 0 guess1 = 1 # get the values of functions parser = Parser() fOf0 = parser.parse(equation).evaluate({'x': guess0}) fOf1 = parser.parse(equation).evaluate({'x': guess1}) x0InSecondDrv = parser.parse( get_parsed_equation(second_derivative)).evaluate({'x': guess0}) # Check if fOf0 * fOf1 < 0: print("Root lies between {} and {}".format(guess0, guess1)) else: quit("Root isn't between {} and {}".format(guess0, guess1)) # print("Function:",function, "Derivative:", first_derivative.doit(), "Second derivative:", second_derivative.doit()) # Set x0 x0 = guess0 if fOf0 * x0InSecondDrv > 0: print("Good convergent initial point") # Start Iteration currentx = 0 x_values = [0] decimalPlaces = 0 noOfIterations = 0 while decimalPlaces <= requiredDecimalPlaces: previousx = x_values.pop() fx = parser.parse(equation).evaluate({'x': previousx}) # F(x) fPrime = parser.parse(get_parsed_equation(first_derivative)).evaluate( {'x': previousx}) # F`(x) currentx = previousx - (float(fx) / float(fPrime)) x_values.append(currentx) # Calculate the error # Get the error value error = abs(currentx - previousx) decimalPlaces = get_zeros(error) noOfIterations += 1 # Printing results print("The root is {}, The error is: {}, No of iterations is: {}".format( currentx, error, noOfIterations))
# Quando um dos critérios de parada do método for atingido # (iterações máximas ou erro definido) seu valor muda para 1. parar = 0 # Define primeiro valor da variável independente # x para se buscar a raiz da função. x0 = -5.0 # Estimativa inicial para a raiz. while parar == 0: iteracao = iteracao + 1 # Incrementa contador de iterações. f_x0 = calcula_f(x0) # Calcula valor da função em x = x0. d = Derivative(calcula_f(x), x) # Calcula derivada da função. # Calcula valor da derivada da função em x = x0. f_linha_x0 = d.doit().subs({x: x0}) # Calcula próxima estimativa para a raiz da função. x1 = x0 - (f_x0 / f_linha_x0) # Calcula o erro entre o valor anterior e o atual. # Usa somente o valor absoluto. erro = abs(x0 - x1) x0 = x1 # Atualiza variável x0 com a nova estimativa. if (iteracao > iteracao_maxima) or (erro < erro_definido): # Se um dos critérios de parada é atingido, muda valor de parar. # parar = 1 faz o loop while encerrar # e o programa terminar sua execução. parar = 1
def test_doit(): n = Symbol('n', integer=True) f = Sum(2 * n * x, (n, 1, 3)) d = Derivative(f, x) assert d.doit() == 12 assert d.doit(deep=False) == Sum(2*n, (n, 1, 3))
#first derivative of f with respect to x d1f_dx = Derivative(f_of_x, x, 1) #second derivative of f with respect to x d2f_dx = Derivative(f_of_x, x, 2) #third derivative of f with respect to x d3f_dx = Derivative(f_of_x, x, 3) print("d1f_dx:", d1f_dx) print("d2f_dx:", d2f_dx) print("d3f_dx:", d3f_dx) print() d1f_dx = d1f_dx.doit() #do it, which means actually evaluate the derivative d2f_dx = d2f_dx.doit() d3f_dx = d3f_dx.doit() print("d1f_dx:", d1f_dx) print("d2f_dx:", d2f_dx) print("d3f_dx:", d3f_dx) """ f_of_x: x**3 d1f_dx: 3*x**2 d2f_dx: 6*x d3f_dx: 6 -------------------------------- d1f_dx: Derivative(x**3, x) d2f_dx: Derivative(x**3, (x, 2)) d3f_dx: Derivative(x**3, (x, 3))
def test_doit(): n = Symbol('n', integer = True) f = Sum(2 * n * x, (n, 1, 3)) d = Derivative(f, x) assert d.doit() == 12 assert d.doit(deep = False) == Sum(2*n, (n, 1, 3))
def get_cumulant(xn, yn, zn): """ :param xn: order of x-nth cumulant :param yn: :param zn: :return: cumulant_xn_yn_zn Order cumulant's subterms: xn + yn + zn ex 5th order = m012*m020 """ x, y, z = symbols('x y z') F = Function('F')(x, y, z) mgf = ln(F) deriv = Derivative(mgf, (x, xn), (y, yn), (z, zn)) all_terms = deriv.doit() all_terms = all_terms * F # Geier: C = c * m000 all_terms = simplify(all_terms) # result = collect(result, F) # Thank you sympy: NotImplementedError: Improve MV Derivative support in collect # so lets start from highest (2,2,2) ... all_terms = all_terms.subs({ sym.Derivative(F, (x, 2), (y, 2), (z, 2)): Symbol('m_{222}'), }) all_terms = all_terms.subs({ sym.Derivative(F, (x, 1), (y, 2), (z, 2)): Symbol('m_{122}'), sym.Derivative(F, (x, 2), (y, 1), (z, 2)): Symbol('m_{212}'), sym.Derivative(F, (x, 2), (y, 2), (z, 1)): Symbol('m_{221}'), }) all_terms = all_terms.subs({ sym.Derivative(F, (x, 0), (y, 2), (z, 2)): Symbol('m_{022}'), sym.Derivative(F, (x, 2), (y, 0), (z, 2)): Symbol('m_{202}'), sym.Derivative(F, (x, 2), (y, 2), (z, 0)): Symbol('m_{220}'), sym.Derivative(F, (x, 2), (y, 1), (z, 1)): Symbol('m_{211}'), sym.Derivative(F, (x, 1), (y, 2), (z, 1)): Symbol('m_{121}'), sym.Derivative(F, (x, 1), (y, 1), (z, 2)): Symbol('m_{112}'), }) pretty_dict = { sym.Derivative(F, (x, 2), (y, 1), (z, 0)): Symbol('m_{210}'), sym.Derivative(F, (x, 1), (y, 2), (z, 0)): Symbol('m_{120}'), sym.Derivative(F, (x, 1), (y, 1), (z, 1)): Symbol('m_{111}'), sym.Derivative(F, (x, 0), (y, 1), (z, 2)): Symbol('m_{012}'), sym.Derivative(F, (x, 0), (y, 2), (z, 1)): Symbol('m_{021}'), sym.Derivative(F, (x, 1), (y, 0), (z, 2)): Symbol('m_{102}'), sym.Derivative(F, (x, 2), (y, 0), (z, 1)): Symbol('m_{201}'), } all_terms = all_terms.subs(pretty_dict) all_terms = all_terms.subs({ sym.Derivative(F, (x, 2)): Symbol('m_{200}'), sym.Derivative(F, (y, 2)): Symbol('m_{020}'), sym.Derivative(F, (z, 2)): Symbol('m_{002}'), sym.Derivative(F, (x, 1), (y, 1), (z, 0)): Symbol('m_{110}'), sym.Derivative(F, (x, 1), (y, 0), (z, 1)): Symbol('m_{101}'), sym.Derivative(F, (x, 0), (y, 1), (z, 1)): Symbol('m_{011}'), }) all_terms = all_terms.subs({ sym.Derivative(F, (x, 1)): Symbol('m_{100}'), sym.Derivative(F, (y, 1)): Symbol('m_{010}'), sym.Derivative(F, (z, 1)): Symbol('m_{001}'), F: Symbol('m_{000}'), }) # all_terms = collect(all_terms, Symbol('m_{100}')) # does nothing all_terms = Poly(all_terms, F).all_terms() all_terms = sum(F ** n * term for (n,), term in all_terms) # order = 4 # given_order_terms = sum(F ** n * term for (n,), term in all_terms if n <= order) # given_order_terms_inv = sum(F ** (-n) * term for (n,), term in all_terms if n <= order) all_terms = simplify(all_terms) # does nothing agan lower_m000_terms = [] # # PYDEVD_USE_FRAME_EVAL = NO for term in all_terms.args: # may crash in debug session... sympy - thank you again ht = Symbol('m_{000}') higher_terms = [ht**(-2), ht**(-3), ht**(-4)] is_lower_order = not any(elem in higher_terms for elem in term.args) if is_lower_order: lower_m000_terms.append(term) # pprint(term) # print("------------------------") # Wolfram Alpha - Derivatives of Abstract Functions # d^2/(dy*dx)(log(f(x,y))) return all_terms, lower_m000_terms